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" 27*276f9e8cSHeejin Ahn #include "WebAssemblySortRegion.h" 28950a13cfSDan Gohman #include "WebAssemblySubtarget.h" 294fc4e42dSDan Gohman #include "WebAssemblyUtilities.h" 30c4ac74fbSHeejin Ahn #include "llvm/ADT/Statistic.h" 3132807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h" 32950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h" 33904cd3e0SReid Kleckner #include "llvm/CodeGen/MachineLoopInfo.h" 34e76fa9ecSHeejin Ahn #include "llvm/MC/MCAsmInfo.h" 35fe0006c8SSimon Pilgrim #include "llvm/Target/TargetMachine.h" 36950a13cfSDan Gohman using namespace llvm; 37*276f9e8cSHeejin Ahn using WebAssembly::SortRegionInfo; 38950a13cfSDan Gohman 39950a13cfSDan Gohman #define DEBUG_TYPE "wasm-cfg-stackify" 40950a13cfSDan Gohman 41c4ac74fbSHeejin Ahn STATISTIC(NumUnwindMismatches, "Number of EH pad unwind mismatches found"); 42c4ac74fbSHeejin Ahn 43950a13cfSDan Gohman namespace { 44950a13cfSDan Gohman class WebAssemblyCFGStackify final : public MachineFunctionPass { 45117296c0SMehdi Amini StringRef getPassName() const override { return "WebAssembly CFG Stackify"; } 46950a13cfSDan Gohman 47950a13cfSDan Gohman void getAnalysisUsage(AnalysisUsage &AU) const override { 4832807932SDan Gohman AU.addRequired<MachineDominatorTree>(); 49950a13cfSDan Gohman AU.addRequired<MachineLoopInfo>(); 50e76fa9ecSHeejin Ahn AU.addRequired<WebAssemblyExceptionInfo>(); 51950a13cfSDan Gohman MachineFunctionPass::getAnalysisUsage(AU); 52950a13cfSDan Gohman } 53950a13cfSDan Gohman 54950a13cfSDan Gohman bool runOnMachineFunction(MachineFunction &MF) override; 55950a13cfSDan Gohman 56e76fa9ecSHeejin Ahn // For each block whose label represents the end of a scope, record the block 57e76fa9ecSHeejin Ahn // which holds the beginning of the scope. This will allow us to quickly skip 58e76fa9ecSHeejin Ahn // over scoped regions when walking blocks. 59e76fa9ecSHeejin Ahn SmallVector<MachineBasicBlock *, 8> ScopeTops; 60e76fa9ecSHeejin Ahn 61c4ac74fbSHeejin Ahn // Placing markers. 62e76fa9ecSHeejin Ahn void placeMarkers(MachineFunction &MF); 63e76fa9ecSHeejin Ahn void placeBlockMarker(MachineBasicBlock &MBB); 64e76fa9ecSHeejin Ahn void placeLoopMarker(MachineBasicBlock &MBB); 65e76fa9ecSHeejin Ahn void placeTryMarker(MachineBasicBlock &MBB); 66cf699b45SHeejin Ahn void removeUnnecessaryInstrs(MachineFunction &MF); 67c4ac74fbSHeejin Ahn bool fixUnwindMismatches(MachineFunction &MF); 68e76fa9ecSHeejin Ahn void rewriteDepthImmediates(MachineFunction &MF); 69e76fa9ecSHeejin Ahn void fixEndsAtEndOfFunction(MachineFunction &MF); 70e76fa9ecSHeejin Ahn 71e76fa9ecSHeejin Ahn // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY). 72e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd; 73e76fa9ecSHeejin Ahn // For each END_(BLOCK|LOOP|TRY), the corresponding BLOCK|LOOP|TRY. 74e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineInstr *> EndToBegin; 75e76fa9ecSHeejin Ahn // <TRY marker, EH pad> map 76e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad; 77e76fa9ecSHeejin Ahn // <EH pad, TRY marker> map 78e76fa9ecSHeejin Ahn DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry; 79e76fa9ecSHeejin Ahn 80c4ac74fbSHeejin Ahn // There can be an appendix block at the end of each function, shared for: 81c4ac74fbSHeejin Ahn // - creating a correct signature for fallthrough returns 82c4ac74fbSHeejin Ahn // - target for rethrows that need to unwind to the caller, but are trapped 83c4ac74fbSHeejin Ahn // inside another try/catch 84c4ac74fbSHeejin Ahn MachineBasicBlock *AppendixBB = nullptr; 85c4ac74fbSHeejin Ahn MachineBasicBlock *getAppendixBlock(MachineFunction &MF) { 86c4ac74fbSHeejin Ahn if (!AppendixBB) { 87c4ac74fbSHeejin Ahn AppendixBB = MF.CreateMachineBasicBlock(); 88c4ac74fbSHeejin Ahn // Give it a fake predecessor so that AsmPrinter prints its label. 89c4ac74fbSHeejin Ahn AppendixBB->addSuccessor(AppendixBB); 90c4ac74fbSHeejin Ahn MF.push_back(AppendixBB); 91c4ac74fbSHeejin Ahn } 92c4ac74fbSHeejin Ahn return AppendixBB; 93c4ac74fbSHeejin Ahn } 94c4ac74fbSHeejin Ahn 95cf699b45SHeejin Ahn // Helper functions to register / unregister scope information created by 96cf699b45SHeejin Ahn // marker instructions. 97e76fa9ecSHeejin Ahn void registerScope(MachineInstr *Begin, MachineInstr *End); 98e76fa9ecSHeejin Ahn void registerTryScope(MachineInstr *Begin, MachineInstr *End, 99e76fa9ecSHeejin Ahn MachineBasicBlock *EHPad); 100cf699b45SHeejin Ahn void unregisterScope(MachineInstr *Begin); 101e76fa9ecSHeejin Ahn 102950a13cfSDan Gohman public: 103950a13cfSDan Gohman static char ID; // Pass identification, replacement for typeid 104950a13cfSDan Gohman WebAssemblyCFGStackify() : MachineFunctionPass(ID) {} 105e76fa9ecSHeejin Ahn ~WebAssemblyCFGStackify() override { releaseMemory(); } 106e76fa9ecSHeejin Ahn void releaseMemory() override; 107950a13cfSDan Gohman }; 108950a13cfSDan Gohman } // end anonymous namespace 109950a13cfSDan Gohman 110950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0; 11140926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE, 112c4ac74fbSHeejin Ahn "Insert BLOCK/LOOP/TRY markers for WebAssembly scopes", false, 113f208f631SHeejin Ahn false) 11440926451SJacob Gravelle 115950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() { 116950a13cfSDan Gohman return new WebAssemblyCFGStackify(); 117950a13cfSDan Gohman } 118950a13cfSDan Gohman 119b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as 120b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized 121b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough 122b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any 123b3aa1ecaSDan Gohman /// explicit mentions. 12418c56a07SHeejin Ahn static bool explicitlyBranchesTo(MachineBasicBlock *Pred, 12535e4a289SDan Gohman MachineBasicBlock *MBB) { 126b3aa1ecaSDan Gohman for (MachineInstr &MI : Pred->terminators()) 127b3aa1ecaSDan Gohman for (MachineOperand &MO : MI.explicit_operands()) 128b3aa1ecaSDan Gohman if (MO.isMBB() && MO.getMBB() == MBB) 129b3aa1ecaSDan Gohman return true; 130b3aa1ecaSDan Gohman return false; 131b3aa1ecaSDan Gohman } 132b3aa1ecaSDan Gohman 133e76fa9ecSHeejin Ahn // Returns an iterator to the earliest position possible within the MBB, 134e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet 135e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains 136e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, AfterSet is only 137e76fa9ecSHeejin Ahn // used for sanity checking. 138e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator 13918c56a07SHeejin Ahn getEarliestInsertPos(MachineBasicBlock *MBB, 140e76fa9ecSHeejin Ahn const SmallPtrSet<const MachineInstr *, 4> &BeforeSet, 141e76fa9ecSHeejin Ahn const SmallPtrSet<const MachineInstr *, 4> &AfterSet) { 142e76fa9ecSHeejin Ahn auto InsertPos = MBB->end(); 143e76fa9ecSHeejin Ahn while (InsertPos != MBB->begin()) { 144e76fa9ecSHeejin Ahn if (BeforeSet.count(&*std::prev(InsertPos))) { 145e76fa9ecSHeejin Ahn #ifndef NDEBUG 146e76fa9ecSHeejin Ahn // Sanity check 147e76fa9ecSHeejin Ahn for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos) 148e76fa9ecSHeejin Ahn assert(!AfterSet.count(&*std::prev(Pos))); 149e76fa9ecSHeejin Ahn #endif 150e76fa9ecSHeejin Ahn break; 151e76fa9ecSHeejin Ahn } 152e76fa9ecSHeejin Ahn --InsertPos; 153e76fa9ecSHeejin Ahn } 154e76fa9ecSHeejin Ahn return InsertPos; 155e76fa9ecSHeejin Ahn } 156e76fa9ecSHeejin Ahn 157e76fa9ecSHeejin Ahn // Returns an iterator to the latest position possible within the MBB, 158e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet 159e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains 160e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, BeforeSet is only 161e76fa9ecSHeejin Ahn // used for sanity checking. 162e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator 16318c56a07SHeejin Ahn getLatestInsertPos(MachineBasicBlock *MBB, 164e76fa9ecSHeejin Ahn const SmallPtrSet<const MachineInstr *, 4> &BeforeSet, 165e76fa9ecSHeejin Ahn const SmallPtrSet<const MachineInstr *, 4> &AfterSet) { 166e76fa9ecSHeejin Ahn auto InsertPos = MBB->begin(); 167e76fa9ecSHeejin Ahn while (InsertPos != MBB->end()) { 168e76fa9ecSHeejin Ahn if (AfterSet.count(&*InsertPos)) { 169e76fa9ecSHeejin Ahn #ifndef NDEBUG 170e76fa9ecSHeejin Ahn // Sanity check 171e76fa9ecSHeejin Ahn for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos) 172e76fa9ecSHeejin Ahn assert(!BeforeSet.count(&*Pos)); 173e76fa9ecSHeejin Ahn #endif 174e76fa9ecSHeejin Ahn break; 175e76fa9ecSHeejin Ahn } 176e76fa9ecSHeejin Ahn ++InsertPos; 177e76fa9ecSHeejin Ahn } 178e76fa9ecSHeejin Ahn return InsertPos; 179e76fa9ecSHeejin Ahn } 180e76fa9ecSHeejin Ahn 181e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin, 182e76fa9ecSHeejin Ahn MachineInstr *End) { 183e76fa9ecSHeejin Ahn BeginToEnd[Begin] = End; 184e76fa9ecSHeejin Ahn EndToBegin[End] = Begin; 185e76fa9ecSHeejin Ahn } 186e76fa9ecSHeejin Ahn 187e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin, 188e76fa9ecSHeejin Ahn MachineInstr *End, 189e76fa9ecSHeejin Ahn MachineBasicBlock *EHPad) { 190e76fa9ecSHeejin Ahn registerScope(Begin, End); 191e76fa9ecSHeejin Ahn TryToEHPad[Begin] = EHPad; 192e76fa9ecSHeejin Ahn EHPadToTry[EHPad] = Begin; 193e76fa9ecSHeejin Ahn } 194e76fa9ecSHeejin Ahn 195cf699b45SHeejin Ahn void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) { 196cf699b45SHeejin Ahn assert(BeginToEnd.count(Begin)); 197cf699b45SHeejin Ahn MachineInstr *End = BeginToEnd[Begin]; 198cf699b45SHeejin Ahn assert(EndToBegin.count(End)); 199cf699b45SHeejin Ahn BeginToEnd.erase(Begin); 200cf699b45SHeejin Ahn EndToBegin.erase(End); 201cf699b45SHeejin Ahn MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin); 202cf699b45SHeejin Ahn if (EHPad) { 203cf699b45SHeejin Ahn assert(EHPadToTry.count(EHPad)); 204cf699b45SHeejin Ahn TryToEHPad.erase(Begin); 205cf699b45SHeejin Ahn EHPadToTry.erase(EHPad); 206cf699b45SHeejin Ahn } 207cf699b45SHeejin Ahn } 208cf699b45SHeejin Ahn 20932807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed). 210c4ac74fbSHeejin Ahn // TODO Consider a more generalized way of handling block (and also loop and 211c4ac74fbSHeejin Ahn // try) signatures when we implement the multi-value proposal later. 212e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) { 21344a5a4b1SHeejin Ahn assert(!MBB.isEHPad()); 214e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 215e76fa9ecSHeejin Ahn auto &MDT = getAnalysis<MachineDominatorTree>(); 216e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 217e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 218e76fa9ecSHeejin Ahn 2198fe7e86bSDan Gohman // First compute the nearest common dominator of all forward non-fallthrough 2208fe7e86bSDan Gohman // predecessors so that we minimize the time that the BLOCK is on the stack, 2218fe7e86bSDan Gohman // which reduces overall stack height. 22232807932SDan Gohman MachineBasicBlock *Header = nullptr; 22332807932SDan Gohman bool IsBranchedTo = false; 224d6f48786SHeejin Ahn bool IsBrOnExn = false; 225d6f48786SHeejin Ahn MachineInstr *BrOnExn = nullptr; 22632807932SDan Gohman int MBBNumber = MBB.getNumber(); 227e76fa9ecSHeejin Ahn for (MachineBasicBlock *Pred : MBB.predecessors()) { 22832807932SDan Gohman if (Pred->getNumber() < MBBNumber) { 22932807932SDan Gohman Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 23018c56a07SHeejin Ahn if (explicitlyBranchesTo(Pred, &MBB)) { 23132807932SDan Gohman IsBranchedTo = true; 232d6f48786SHeejin Ahn if (Pred->getFirstTerminator()->getOpcode() == WebAssembly::BR_ON_EXN) { 233d6f48786SHeejin Ahn IsBrOnExn = true; 234d6f48786SHeejin Ahn assert(!BrOnExn && "There should be only one br_on_exn per block"); 235d6f48786SHeejin Ahn BrOnExn = &*Pred->getFirstTerminator(); 236d6f48786SHeejin Ahn } 237d6f48786SHeejin Ahn } 23832807932SDan Gohman } 239e76fa9ecSHeejin Ahn } 24032807932SDan Gohman if (!Header) 24132807932SDan Gohman return; 24232807932SDan Gohman if (!IsBranchedTo) 24332807932SDan Gohman return; 24432807932SDan Gohman 2458fe7e86bSDan Gohman assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors"); 2465c644c9bSHeejin Ahn MachineBasicBlock *LayoutPred = MBB.getPrevNode(); 2478fe7e86bSDan Gohman 2488fe7e86bSDan Gohman // If the nearest common dominator is inside a more deeply nested context, 2498fe7e86bSDan Gohman // walk out to the nearest scope which isn't more deeply nested. 2508fe7e86bSDan Gohman for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 2518fe7e86bSDan Gohman if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 2528fe7e86bSDan Gohman if (ScopeTop->getNumber() > Header->getNumber()) { 2538fe7e86bSDan Gohman // Skip over an intervening scope. 2545c644c9bSHeejin Ahn I = std::next(ScopeTop->getIterator()); 2558fe7e86bSDan Gohman } else { 2568fe7e86bSDan Gohman // We found a scope level at an appropriate depth. 2578fe7e86bSDan Gohman Header = ScopeTop; 2588fe7e86bSDan Gohman break; 2598fe7e86bSDan Gohman } 2608fe7e86bSDan Gohman } 2618fe7e86bSDan Gohman } 2628fe7e86bSDan Gohman 2638fe7e86bSDan Gohman // Decide where in Header to put the BLOCK. 264e76fa9ecSHeejin Ahn 265e76fa9ecSHeejin Ahn // Instructions that should go before the BLOCK. 266e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 267e76fa9ecSHeejin Ahn // Instructions that should go after the BLOCK. 268e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 269e76fa9ecSHeejin Ahn for (const auto &MI : *Header) { 27044a5a4b1SHeejin Ahn // If there is a previously placed LOOP marker and the bottom block of the 27144a5a4b1SHeejin Ahn // loop is above MBB, it should be after the BLOCK, because the loop is 27244a5a4b1SHeejin Ahn // nested in this BLOCK. Otherwise it should be before the BLOCK. 27344a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP) { 27444a5a4b1SHeejin Ahn auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode(); 27544a5a4b1SHeejin Ahn if (MBB.getNumber() > LoopBottom->getNumber()) 276e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 277e76fa9ecSHeejin Ahn #ifndef NDEBUG 278e76fa9ecSHeejin Ahn else 279e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 280e76fa9ecSHeejin Ahn #endif 281e76fa9ecSHeejin Ahn } 282e76fa9ecSHeejin Ahn 283834debffSHeejin Ahn // If there is a previously placed BLOCK/TRY marker and its corresponding 284834debffSHeejin Ahn // END marker is before the current BLOCK's END marker, that should be 285834debffSHeejin Ahn // placed after this BLOCK. Otherwise it should be placed before this BLOCK 286834debffSHeejin Ahn // marker. 28744a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::BLOCK || 288834debffSHeejin Ahn MI.getOpcode() == WebAssembly::TRY) { 289834debffSHeejin Ahn if (BeginToEnd[&MI]->getParent()->getNumber() <= MBB.getNumber()) 290e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 291834debffSHeejin Ahn #ifndef NDEBUG 292834debffSHeejin Ahn else 293834debffSHeejin Ahn BeforeSet.insert(&MI); 294834debffSHeejin Ahn #endif 295834debffSHeejin Ahn } 296e76fa9ecSHeejin Ahn 297e76fa9ecSHeejin Ahn #ifndef NDEBUG 298e76fa9ecSHeejin Ahn // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK. 299e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_BLOCK || 300e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_LOOP || 301e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) 302e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 303e76fa9ecSHeejin Ahn #endif 304e76fa9ecSHeejin Ahn 305e76fa9ecSHeejin Ahn // Terminators should go after the BLOCK. 306e76fa9ecSHeejin Ahn if (MI.isTerminator()) 307e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 308e76fa9ecSHeejin Ahn } 309e76fa9ecSHeejin Ahn 310e76fa9ecSHeejin Ahn // Local expression tree should go after the BLOCK. 311e76fa9ecSHeejin Ahn for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E; 312e76fa9ecSHeejin Ahn --I) { 313409b4391SYury Delendik if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 314409b4391SYury Delendik continue; 315e76fa9ecSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI)) 316e76fa9ecSHeejin Ahn AfterSet.insert(&*std::prev(I)); 317e76fa9ecSHeejin Ahn else 318e76fa9ecSHeejin Ahn break; 31932807932SDan Gohman } 32032807932SDan Gohman 3218fe7e86bSDan Gohman // Add the BLOCK. 322d6f48786SHeejin Ahn 3239f96a58cSHeejin Ahn // 'br_on_exn' extracts exnref object and pushes variable number of values 324d6f48786SHeejin Ahn // depending on its tag. For C++ exception, its a single i32 value, and the 325d6f48786SHeejin Ahn // generated code will be in the form of: 326d6f48786SHeejin Ahn // block i32 327d6f48786SHeejin Ahn // br_on_exn 0, $__cpp_exception 328d6f48786SHeejin Ahn // rethrow 329d6f48786SHeejin Ahn // end_block 3302cb27072SThomas Lively WebAssembly::BlockType ReturnType = WebAssembly::BlockType::Void; 331d6f48786SHeejin Ahn if (IsBrOnExn) { 332d6f48786SHeejin Ahn const char *TagName = BrOnExn->getOperand(1).getSymbolName(); 333d6f48786SHeejin Ahn if (std::strcmp(TagName, "__cpp_exception") != 0) 334d6f48786SHeejin Ahn llvm_unreachable("Only C++ exception is supported"); 3352cb27072SThomas Lively ReturnType = WebAssembly::BlockType::I32; 336d6f48786SHeejin Ahn } 337d6f48786SHeejin Ahn 33818c56a07SHeejin Ahn auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet); 33992401cc1SHeejin Ahn MachineInstr *Begin = 34092401cc1SHeejin Ahn BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 3412726b88cSDan Gohman TII.get(WebAssembly::BLOCK)) 342d6f48786SHeejin Ahn .addImm(int64_t(ReturnType)); 3431d68e80fSDan Gohman 344e76fa9ecSHeejin Ahn // Decide where in Header to put the END_BLOCK. 345e76fa9ecSHeejin Ahn BeforeSet.clear(); 346e76fa9ecSHeejin Ahn AfterSet.clear(); 347e76fa9ecSHeejin Ahn for (auto &MI : MBB) { 348e76fa9ecSHeejin Ahn #ifndef NDEBUG 349e76fa9ecSHeejin Ahn // END_BLOCK should precede existing LOOP and TRY markers. 350e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP || 351e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::TRY) 352e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 353e76fa9ecSHeejin Ahn #endif 354e76fa9ecSHeejin Ahn 355e76fa9ecSHeejin Ahn // If there is a previously placed END_LOOP marker and the header of the 356e76fa9ecSHeejin Ahn // loop is above this block's header, the END_LOOP should be placed after 357e76fa9ecSHeejin Ahn // the BLOCK, because the loop contains this block. Otherwise the END_LOOP 358e76fa9ecSHeejin Ahn // should be placed before the BLOCK. The same for END_TRY. 359e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP || 360e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) { 361e76fa9ecSHeejin Ahn if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber()) 362e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 363e76fa9ecSHeejin Ahn #ifndef NDEBUG 364e76fa9ecSHeejin Ahn else 365e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 366e76fa9ecSHeejin Ahn #endif 367e76fa9ecSHeejin Ahn } 368e76fa9ecSHeejin Ahn } 369e76fa9ecSHeejin Ahn 3701d68e80fSDan Gohman // Mark the end of the block. 37118c56a07SHeejin Ahn InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet); 37210b31358SDerek Schuff MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos), 3732726b88cSDan Gohman TII.get(WebAssembly::END_BLOCK)); 374e76fa9ecSHeejin Ahn registerScope(Begin, End); 3758fe7e86bSDan Gohman 3768fe7e86bSDan Gohman // Track the farthest-spanning scope that ends at this point. 3778fe7e86bSDan Gohman int Number = MBB.getNumber(); 3788fe7e86bSDan Gohman if (!ScopeTops[Number] || 3798fe7e86bSDan Gohman ScopeTops[Number]->getNumber() > Header->getNumber()) 3808fe7e86bSDan Gohman ScopeTops[Number] = Header; 381950a13cfSDan Gohman } 382950a13cfSDan Gohman 3838fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header). 384e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) { 385e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 386e76fa9ecSHeejin Ahn const auto &MLI = getAnalysis<MachineLoopInfo>(); 387*276f9e8cSHeejin Ahn const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>(); 388*276f9e8cSHeejin Ahn SortRegionInfo SRI(MLI, WEI); 389e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 390e76fa9ecSHeejin Ahn 3918fe7e86bSDan Gohman MachineLoop *Loop = MLI.getLoopFor(&MBB); 3928fe7e86bSDan Gohman if (!Loop || Loop->getHeader() != &MBB) 3938fe7e86bSDan Gohman return; 3948fe7e86bSDan Gohman 3958fe7e86bSDan Gohman // The operand of a LOOP is the first block after the loop. If the loop is the 3968fe7e86bSDan Gohman // bottom of the function, insert a dummy block at the end. 397*276f9e8cSHeejin Ahn MachineBasicBlock *Bottom = SRI.getBottom(Loop); 3985c644c9bSHeejin Ahn auto Iter = std::next(Bottom->getIterator()); 399e3e4a5ffSDan Gohman if (Iter == MF.end()) { 400c4ac74fbSHeejin Ahn getAppendixBlock(MF); 4015c644c9bSHeejin Ahn Iter = std::next(Bottom->getIterator()); 402e3e4a5ffSDan Gohman } 4038fe7e86bSDan Gohman MachineBasicBlock *AfterLoop = &*Iter; 404f6857223SDan Gohman 405e76fa9ecSHeejin Ahn // Decide where in Header to put the LOOP. 406e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 407e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 408e76fa9ecSHeejin Ahn for (const auto &MI : MBB) { 409e76fa9ecSHeejin Ahn // LOOP marker should be after any existing loop that ends here. Otherwise 410e76fa9ecSHeejin Ahn // we assume the instruction belongs to the loop. 411e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) 412e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 413e76fa9ecSHeejin Ahn #ifndef NDEBUG 414e76fa9ecSHeejin Ahn else 415e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 416e76fa9ecSHeejin Ahn #endif 417e76fa9ecSHeejin Ahn } 418e76fa9ecSHeejin Ahn 419e76fa9ecSHeejin Ahn // Mark the beginning of the loop. 42018c56a07SHeejin Ahn auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet); 42110b31358SDerek Schuff MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos), 4222726b88cSDan Gohman TII.get(WebAssembly::LOOP)) 4232cb27072SThomas Lively .addImm(int64_t(WebAssembly::BlockType::Void)); 4241d68e80fSDan Gohman 425e76fa9ecSHeejin Ahn // Decide where in Header to put the END_LOOP. 426e76fa9ecSHeejin Ahn BeforeSet.clear(); 427e76fa9ecSHeejin Ahn AfterSet.clear(); 428e76fa9ecSHeejin Ahn #ifndef NDEBUG 429e76fa9ecSHeejin Ahn for (const auto &MI : MBB) 430e76fa9ecSHeejin Ahn // Existing END_LOOP markers belong to parent loops of this loop 431e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) 432e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 433e76fa9ecSHeejin Ahn #endif 434e76fa9ecSHeejin Ahn 435e76fa9ecSHeejin Ahn // Mark the end of the loop (using arbitrary debug location that branched to 436e76fa9ecSHeejin Ahn // the loop end as its location). 43718c56a07SHeejin Ahn InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet); 43867f74aceSHeejin Ahn DebugLoc EndDL = AfterLoop->pred_empty() 43967f74aceSHeejin Ahn ? DebugLoc() 44067f74aceSHeejin Ahn : (*AfterLoop->pred_rbegin())->findBranchDebugLoc(); 441e76fa9ecSHeejin Ahn MachineInstr *End = 442e76fa9ecSHeejin Ahn BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP)); 443e76fa9ecSHeejin Ahn registerScope(Begin, End); 4448fe7e86bSDan Gohman 4458fe7e86bSDan Gohman assert((!ScopeTops[AfterLoop->getNumber()] || 4468fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) && 447442bfcecSDan Gohman "With block sorting the outermost loop for a block should be first."); 4488fe7e86bSDan Gohman if (!ScopeTops[AfterLoop->getNumber()]) 4498fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()] = &MBB; 450e3e4a5ffSDan Gohman } 451950a13cfSDan Gohman 452e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) { 45344a5a4b1SHeejin Ahn assert(MBB.isEHPad()); 454e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 455e76fa9ecSHeejin Ahn auto &MDT = getAnalysis<MachineDominatorTree>(); 456e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 457*276f9e8cSHeejin Ahn const auto &MLI = getAnalysis<MachineLoopInfo>(); 458e76fa9ecSHeejin Ahn const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>(); 459*276f9e8cSHeejin Ahn SortRegionInfo SRI(MLI, WEI); 460e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 461e76fa9ecSHeejin Ahn 462e76fa9ecSHeejin Ahn // Compute the nearest common dominator of all unwind predecessors 463e76fa9ecSHeejin Ahn MachineBasicBlock *Header = nullptr; 464e76fa9ecSHeejin Ahn int MBBNumber = MBB.getNumber(); 465e76fa9ecSHeejin Ahn for (auto *Pred : MBB.predecessors()) { 466e76fa9ecSHeejin Ahn if (Pred->getNumber() < MBBNumber) { 467e76fa9ecSHeejin Ahn Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 46818c56a07SHeejin Ahn assert(!explicitlyBranchesTo(Pred, &MBB) && 469e76fa9ecSHeejin Ahn "Explicit branch to an EH pad!"); 470e76fa9ecSHeejin Ahn } 471e76fa9ecSHeejin Ahn } 472e76fa9ecSHeejin Ahn if (!Header) 473e76fa9ecSHeejin Ahn return; 474e76fa9ecSHeejin Ahn 475e76fa9ecSHeejin Ahn // If this try is at the bottom of the function, insert a dummy block at the 476e76fa9ecSHeejin Ahn // end. 477e76fa9ecSHeejin Ahn WebAssemblyException *WE = WEI.getExceptionFor(&MBB); 478e76fa9ecSHeejin Ahn assert(WE); 479*276f9e8cSHeejin Ahn MachineBasicBlock *Bottom = SRI.getBottom(WE); 480e76fa9ecSHeejin Ahn 4815c644c9bSHeejin Ahn auto Iter = std::next(Bottom->getIterator()); 482e76fa9ecSHeejin Ahn if (Iter == MF.end()) { 483c4ac74fbSHeejin Ahn getAppendixBlock(MF); 4845c644c9bSHeejin Ahn Iter = std::next(Bottom->getIterator()); 485e76fa9ecSHeejin Ahn } 48620cf0749SHeejin Ahn MachineBasicBlock *Cont = &*Iter; 487e76fa9ecSHeejin Ahn 48820cf0749SHeejin Ahn assert(Cont != &MF.front()); 4895c644c9bSHeejin Ahn MachineBasicBlock *LayoutPred = Cont->getPrevNode(); 490e76fa9ecSHeejin Ahn 491e76fa9ecSHeejin Ahn // If the nearest common dominator is inside a more deeply nested context, 492e76fa9ecSHeejin Ahn // walk out to the nearest scope which isn't more deeply nested. 493e76fa9ecSHeejin Ahn for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 494e76fa9ecSHeejin Ahn if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 495e76fa9ecSHeejin Ahn if (ScopeTop->getNumber() > Header->getNumber()) { 496e76fa9ecSHeejin Ahn // Skip over an intervening scope. 4975c644c9bSHeejin Ahn I = std::next(ScopeTop->getIterator()); 498e76fa9ecSHeejin Ahn } else { 499e76fa9ecSHeejin Ahn // We found a scope level at an appropriate depth. 500e76fa9ecSHeejin Ahn Header = ScopeTop; 501e76fa9ecSHeejin Ahn break; 502e76fa9ecSHeejin Ahn } 503e76fa9ecSHeejin Ahn } 504e76fa9ecSHeejin Ahn } 505e76fa9ecSHeejin Ahn 506e76fa9ecSHeejin Ahn // Decide where in Header to put the TRY. 507e76fa9ecSHeejin Ahn 50844a5a4b1SHeejin Ahn // Instructions that should go before the TRY. 509e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 51044a5a4b1SHeejin Ahn // Instructions that should go after the TRY. 511e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 512e76fa9ecSHeejin Ahn for (const auto &MI : *Header) { 51344a5a4b1SHeejin Ahn // If there is a previously placed LOOP marker and the bottom block of the 51444a5a4b1SHeejin Ahn // loop is above MBB, it should be after the TRY, because the loop is nested 51544a5a4b1SHeejin Ahn // in this TRY. Otherwise it should be before the TRY. 516e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP) { 51744a5a4b1SHeejin Ahn auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode(); 51844a5a4b1SHeejin Ahn if (MBB.getNumber() > LoopBottom->getNumber()) 519e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 520e76fa9ecSHeejin Ahn #ifndef NDEBUG 521e76fa9ecSHeejin Ahn else 522e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 523e76fa9ecSHeejin Ahn #endif 524e76fa9ecSHeejin Ahn } 525e76fa9ecSHeejin Ahn 52644a5a4b1SHeejin Ahn // All previously inserted BLOCK/TRY markers should be after the TRY because 52744a5a4b1SHeejin Ahn // they are all nested trys. 52844a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::BLOCK || 52944a5a4b1SHeejin Ahn MI.getOpcode() == WebAssembly::TRY) 530e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 531e76fa9ecSHeejin Ahn 532e76fa9ecSHeejin Ahn #ifndef NDEBUG 53344a5a4b1SHeejin Ahn // All END_(BLOCK/LOOP/TRY) markers should be before the TRY. 53444a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::END_BLOCK || 53544a5a4b1SHeejin Ahn MI.getOpcode() == WebAssembly::END_LOOP || 536e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) 537e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 538e76fa9ecSHeejin Ahn #endif 539e76fa9ecSHeejin Ahn 540e76fa9ecSHeejin Ahn // Terminators should go after the TRY. 541e76fa9ecSHeejin Ahn if (MI.isTerminator()) 542e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 543e76fa9ecSHeejin Ahn } 544e76fa9ecSHeejin Ahn 5456a37c5d6SHeejin Ahn // If Header unwinds to MBB (= Header contains 'invoke'), the try block should 5466a37c5d6SHeejin Ahn // contain the call within it. So the call should go after the TRY. The 5476a37c5d6SHeejin Ahn // exception is when the header's terminator is a rethrow instruction, in 5486a37c5d6SHeejin Ahn // which case that instruction, not a call instruction before it, is gonna 5496a37c5d6SHeejin Ahn // throw. 5506a37c5d6SHeejin Ahn MachineInstr *ThrowingCall = nullptr; 5516a37c5d6SHeejin Ahn if (MBB.isPredecessor(Header)) { 5526a37c5d6SHeejin Ahn auto TermPos = Header->getFirstTerminator(); 5536a37c5d6SHeejin Ahn if (TermPos == Header->end() || 5546a37c5d6SHeejin Ahn TermPos->getOpcode() != WebAssembly::RETHROW) { 5556a37c5d6SHeejin Ahn for (auto &MI : reverse(*Header)) { 5566a37c5d6SHeejin Ahn if (MI.isCall()) { 5576a37c5d6SHeejin Ahn AfterSet.insert(&MI); 5586a37c5d6SHeejin Ahn ThrowingCall = &MI; 5596a37c5d6SHeejin Ahn // Possibly throwing calls are usually wrapped by EH_LABEL 5606a37c5d6SHeejin Ahn // instructions. We don't want to split them and the call. 5616a37c5d6SHeejin Ahn if (MI.getIterator() != Header->begin() && 5626a37c5d6SHeejin Ahn std::prev(MI.getIterator())->isEHLabel()) { 5636a37c5d6SHeejin Ahn AfterSet.insert(&*std::prev(MI.getIterator())); 5646a37c5d6SHeejin Ahn ThrowingCall = &*std::prev(MI.getIterator()); 5656a37c5d6SHeejin Ahn } 5666a37c5d6SHeejin Ahn break; 5676a37c5d6SHeejin Ahn } 5686a37c5d6SHeejin Ahn } 5696a37c5d6SHeejin Ahn } 5706a37c5d6SHeejin Ahn } 5716a37c5d6SHeejin Ahn 572e76fa9ecSHeejin Ahn // Local expression tree should go after the TRY. 5736a37c5d6SHeejin Ahn // For BLOCK placement, we start the search from the previous instruction of a 5746a37c5d6SHeejin Ahn // BB's terminator, but in TRY's case, we should start from the previous 5756a37c5d6SHeejin Ahn // instruction of a call that can throw, or a EH_LABEL that precedes the call, 5766a37c5d6SHeejin Ahn // because the return values of the call's previous instructions can be 5776a37c5d6SHeejin Ahn // stackified and consumed by the throwing call. 5786a37c5d6SHeejin Ahn auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall) 5796a37c5d6SHeejin Ahn : Header->getFirstTerminator(); 5806a37c5d6SHeejin Ahn for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) { 581409b4391SYury Delendik if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 582409b4391SYury Delendik continue; 583e76fa9ecSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI)) 584e76fa9ecSHeejin Ahn AfterSet.insert(&*std::prev(I)); 585e76fa9ecSHeejin Ahn else 586e76fa9ecSHeejin Ahn break; 587e76fa9ecSHeejin Ahn } 588e76fa9ecSHeejin Ahn 589e76fa9ecSHeejin Ahn // Add the TRY. 59018c56a07SHeejin Ahn auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet); 591e76fa9ecSHeejin Ahn MachineInstr *Begin = 592e76fa9ecSHeejin Ahn BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 593e76fa9ecSHeejin Ahn TII.get(WebAssembly::TRY)) 5942cb27072SThomas Lively .addImm(int64_t(WebAssembly::BlockType::Void)); 595e76fa9ecSHeejin Ahn 596e76fa9ecSHeejin Ahn // Decide where in Header to put the END_TRY. 597e76fa9ecSHeejin Ahn BeforeSet.clear(); 598e76fa9ecSHeejin Ahn AfterSet.clear(); 59920cf0749SHeejin Ahn for (const auto &MI : *Cont) { 600e76fa9ecSHeejin Ahn #ifndef NDEBUG 60144a5a4b1SHeejin Ahn // END_TRY should precede existing LOOP and BLOCK markers. 60244a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP || 60344a5a4b1SHeejin Ahn MI.getOpcode() == WebAssembly::BLOCK) 604e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 605e76fa9ecSHeejin Ahn 606e76fa9ecSHeejin Ahn // All END_TRY markers placed earlier belong to exceptions that contains 607e76fa9ecSHeejin Ahn // this one. 608e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_TRY) 609e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 610e76fa9ecSHeejin Ahn #endif 611e76fa9ecSHeejin Ahn 612e76fa9ecSHeejin Ahn // If there is a previously placed END_LOOP marker and its header is after 613e76fa9ecSHeejin Ahn // where TRY marker is, this loop is contained within the 'catch' part, so 614e76fa9ecSHeejin Ahn // the END_TRY marker should go after that. Otherwise, the whole try-catch 615e76fa9ecSHeejin Ahn // is contained within this loop, so the END_TRY should go before that. 616e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) { 617222718fdSHeejin Ahn // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they 618222718fdSHeejin Ahn // are in the same BB, LOOP is always before TRY. 619222718fdSHeejin Ahn if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber()) 620e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 621e76fa9ecSHeejin Ahn #ifndef NDEBUG 622e76fa9ecSHeejin Ahn else 623e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 624e76fa9ecSHeejin Ahn #endif 625e76fa9ecSHeejin Ahn } 62644a5a4b1SHeejin Ahn 62744a5a4b1SHeejin Ahn // It is not possible for an END_BLOCK to be already in this block. 628e76fa9ecSHeejin Ahn } 629e76fa9ecSHeejin Ahn 630e76fa9ecSHeejin Ahn // Mark the end of the TRY. 63120cf0749SHeejin Ahn InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet); 632e76fa9ecSHeejin Ahn MachineInstr *End = 63320cf0749SHeejin Ahn BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(), 634e76fa9ecSHeejin Ahn TII.get(WebAssembly::END_TRY)); 635e76fa9ecSHeejin Ahn registerTryScope(Begin, End, &MBB); 636e76fa9ecSHeejin Ahn 63782da1ffcSHeejin Ahn // Track the farthest-spanning scope that ends at this point. We create two 63882da1ffcSHeejin Ahn // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB 63982da1ffcSHeejin Ahn // with 'try'). We need to create 'catch' -> 'try' mapping here too because 64082da1ffcSHeejin Ahn // markers should not span across 'catch'. For example, this should not 64182da1ffcSHeejin Ahn // happen: 64282da1ffcSHeejin Ahn // 64382da1ffcSHeejin Ahn // try 64482da1ffcSHeejin Ahn // block --| (X) 64582da1ffcSHeejin Ahn // catch | 64682da1ffcSHeejin Ahn // end_block --| 64782da1ffcSHeejin Ahn // end_try 64882da1ffcSHeejin Ahn for (int Number : {Cont->getNumber(), MBB.getNumber()}) { 649e76fa9ecSHeejin Ahn if (!ScopeTops[Number] || 650e76fa9ecSHeejin Ahn ScopeTops[Number]->getNumber() > Header->getNumber()) 651e76fa9ecSHeejin Ahn ScopeTops[Number] = Header; 652e76fa9ecSHeejin Ahn } 65382da1ffcSHeejin Ahn } 654e76fa9ecSHeejin Ahn 655cf699b45SHeejin Ahn void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) { 656cf699b45SHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 657cf699b45SHeejin Ahn 658cf699b45SHeejin Ahn // When there is an unconditional branch right before a catch instruction and 659cf699b45SHeejin Ahn // it branches to the end of end_try marker, we don't need the branch, because 660cf699b45SHeejin Ahn // it there is no exception, the control flow transfers to that point anyway. 661cf699b45SHeejin Ahn // bb0: 662cf699b45SHeejin Ahn // try 663cf699b45SHeejin Ahn // ... 664cf699b45SHeejin Ahn // br bb2 <- Not necessary 665cf699b45SHeejin Ahn // bb1: 666cf699b45SHeejin Ahn // catch 667cf699b45SHeejin Ahn // ... 668cf699b45SHeejin Ahn // bb2: 669cf699b45SHeejin Ahn // end 670cf699b45SHeejin Ahn for (auto &MBB : MF) { 671cf699b45SHeejin Ahn if (!MBB.isEHPad()) 672cf699b45SHeejin Ahn continue; 673cf699b45SHeejin Ahn 674cf699b45SHeejin Ahn MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 675cf699b45SHeejin Ahn SmallVector<MachineOperand, 4> Cond; 6765c644c9bSHeejin Ahn MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode(); 677cf699b45SHeejin Ahn MachineBasicBlock *Cont = BeginToEnd[EHPadToTry[&MBB]]->getParent(); 678cf699b45SHeejin Ahn bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond); 6793fe6ea46SHeejin Ahn // This condition means either 6803fe6ea46SHeejin Ahn // 1. This BB ends with a single unconditional branch whose destinaion is 6813fe6ea46SHeejin Ahn // Cont. 6823fe6ea46SHeejin Ahn // 2. This BB ends with a conditional branch followed by an unconditional 6833fe6ea46SHeejin Ahn // branch, and the unconditional branch's destination is Cont. 6843fe6ea46SHeejin Ahn // In both cases, we want to remove the last (= unconditional) branch. 685cf699b45SHeejin Ahn if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) || 6863fe6ea46SHeejin Ahn (!Cond.empty() && FBB && FBB == Cont))) { 6873fe6ea46SHeejin Ahn bool ErasedUncondBr = false; 688a5099ad9SHeejin Ahn (void)ErasedUncondBr; 6893fe6ea46SHeejin Ahn for (auto I = EHPadLayoutPred->end(), E = EHPadLayoutPred->begin(); 6903fe6ea46SHeejin Ahn I != E; --I) { 6913fe6ea46SHeejin Ahn auto PrevI = std::prev(I); 6923fe6ea46SHeejin Ahn if (PrevI->isTerminator()) { 6933fe6ea46SHeejin Ahn assert(PrevI->getOpcode() == WebAssembly::BR); 6943fe6ea46SHeejin Ahn PrevI->eraseFromParent(); 6953fe6ea46SHeejin Ahn ErasedUncondBr = true; 6963fe6ea46SHeejin Ahn break; 6973fe6ea46SHeejin Ahn } 6983fe6ea46SHeejin Ahn } 6993fe6ea46SHeejin Ahn assert(ErasedUncondBr && "Unconditional branch not erased!"); 7003fe6ea46SHeejin Ahn } 701cf699b45SHeejin Ahn } 702cf699b45SHeejin Ahn 703cf699b45SHeejin Ahn // When there are block / end_block markers that overlap with try / end_try 704cf699b45SHeejin Ahn // markers, and the block and try markers' return types are the same, the 705cf699b45SHeejin Ahn // block /end_block markers are not necessary, because try / end_try markers 706cf699b45SHeejin Ahn // also can serve as boundaries for branches. 707cf699b45SHeejin Ahn // block <- Not necessary 708cf699b45SHeejin Ahn // try 709cf699b45SHeejin Ahn // ... 710cf699b45SHeejin Ahn // catch 711cf699b45SHeejin Ahn // ... 712cf699b45SHeejin Ahn // end 713cf699b45SHeejin Ahn // end <- Not necessary 714cf699b45SHeejin Ahn SmallVector<MachineInstr *, 32> ToDelete; 715cf699b45SHeejin Ahn for (auto &MBB : MF) { 716cf699b45SHeejin Ahn for (auto &MI : MBB) { 717cf699b45SHeejin Ahn if (MI.getOpcode() != WebAssembly::TRY) 718cf699b45SHeejin Ahn continue; 719cf699b45SHeejin Ahn 720cf699b45SHeejin Ahn MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try]; 721cf699b45SHeejin Ahn MachineBasicBlock *TryBB = Try->getParent(); 722cf699b45SHeejin Ahn MachineBasicBlock *Cont = EndTry->getParent(); 723cf699b45SHeejin Ahn int64_t RetType = Try->getOperand(0).getImm(); 7245c644c9bSHeejin Ahn for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator()); 725cf699b45SHeejin Ahn B != TryBB->begin() && E != Cont->end() && 726cf699b45SHeejin Ahn std::prev(B)->getOpcode() == WebAssembly::BLOCK && 727cf699b45SHeejin Ahn E->getOpcode() == WebAssembly::END_BLOCK && 728cf699b45SHeejin Ahn std::prev(B)->getOperand(0).getImm() == RetType; 729cf699b45SHeejin Ahn --B, ++E) { 730cf699b45SHeejin Ahn ToDelete.push_back(&*std::prev(B)); 731cf699b45SHeejin Ahn ToDelete.push_back(&*E); 732cf699b45SHeejin Ahn } 733cf699b45SHeejin Ahn } 734cf699b45SHeejin Ahn } 735cf699b45SHeejin Ahn for (auto *MI : ToDelete) { 736cf699b45SHeejin Ahn if (MI->getOpcode() == WebAssembly::BLOCK) 737cf699b45SHeejin Ahn unregisterScope(MI); 738cf699b45SHeejin Ahn MI->eraseFromParent(); 739cf699b45SHeejin Ahn } 740cf699b45SHeejin Ahn } 741cf699b45SHeejin Ahn 74283c26eaeSHeejin Ahn // Get the appropriate copy opcode for the given register class. 74383c26eaeSHeejin Ahn static unsigned getCopyOpcode(const TargetRegisterClass *RC) { 74483c26eaeSHeejin Ahn if (RC == &WebAssembly::I32RegClass) 74583c26eaeSHeejin Ahn return WebAssembly::COPY_I32; 74683c26eaeSHeejin Ahn if (RC == &WebAssembly::I64RegClass) 74783c26eaeSHeejin Ahn return WebAssembly::COPY_I64; 74883c26eaeSHeejin Ahn if (RC == &WebAssembly::F32RegClass) 74983c26eaeSHeejin Ahn return WebAssembly::COPY_F32; 75083c26eaeSHeejin Ahn if (RC == &WebAssembly::F64RegClass) 75183c26eaeSHeejin Ahn return WebAssembly::COPY_F64; 75283c26eaeSHeejin Ahn if (RC == &WebAssembly::V128RegClass) 75383c26eaeSHeejin Ahn return WebAssembly::COPY_V128; 75483c26eaeSHeejin Ahn if (RC == &WebAssembly::EXNREFRegClass) 75583c26eaeSHeejin Ahn return WebAssembly::COPY_EXNREF; 75683c26eaeSHeejin Ahn llvm_unreachable("Unexpected register class"); 75783c26eaeSHeejin Ahn } 75883c26eaeSHeejin Ahn 75961d5c76aSHeejin Ahn // When MBB is split into MBB and Split, we should unstackify defs in MBB that 76061d5c76aSHeejin Ahn // have their uses in Split. 76161d5c76aSHeejin Ahn static void unstackifyVRegsUsedInSplitBB(MachineBasicBlock &MBB, 76261d5c76aSHeejin Ahn MachineBasicBlock &Split, 76361d5c76aSHeejin Ahn WebAssemblyFunctionInfo &MFI, 76483c26eaeSHeejin Ahn MachineRegisterInfo &MRI, 76583c26eaeSHeejin Ahn const WebAssemblyInstrInfo &TII) { 76661d5c76aSHeejin Ahn for (auto &MI : Split) { 76761d5c76aSHeejin Ahn for (auto &MO : MI.explicit_uses()) { 76861d5c76aSHeejin Ahn if (!MO.isReg() || Register::isPhysicalRegister(MO.getReg())) 76961d5c76aSHeejin Ahn continue; 77061d5c76aSHeejin Ahn if (MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg())) 77161d5c76aSHeejin Ahn if (Def->getParent() == &MBB) 77261d5c76aSHeejin Ahn MFI.unstackifyVReg(MO.getReg()); 77361d5c76aSHeejin Ahn } 77461d5c76aSHeejin Ahn } 77583c26eaeSHeejin Ahn 77683c26eaeSHeejin Ahn // In RegStackify, when a register definition is used multiple times, 77783c26eaeSHeejin Ahn // Reg = INST ... 77883c26eaeSHeejin Ahn // INST ..., Reg, ... 77983c26eaeSHeejin Ahn // INST ..., Reg, ... 78083c26eaeSHeejin Ahn // INST ..., Reg, ... 78183c26eaeSHeejin Ahn // 78283c26eaeSHeejin Ahn // we introduce a TEE, which has the following form: 78383c26eaeSHeejin Ahn // DefReg = INST ... 78483c26eaeSHeejin Ahn // TeeReg, Reg = TEE_... DefReg 78583c26eaeSHeejin Ahn // INST ..., TeeReg, ... 78683c26eaeSHeejin Ahn // INST ..., Reg, ... 78783c26eaeSHeejin Ahn // INST ..., Reg, ... 78883c26eaeSHeejin Ahn // with DefReg and TeeReg stackified but Reg not stackified. 78983c26eaeSHeejin Ahn // 79083c26eaeSHeejin Ahn // But the invariant that TeeReg should be stackified can be violated while we 79183c26eaeSHeejin Ahn // unstackify registers in the split BB above. In this case, we convert TEEs 79283c26eaeSHeejin Ahn // into two COPYs. This COPY will be eventually eliminated in ExplicitLocals. 79383c26eaeSHeejin Ahn // DefReg = INST ... 79483c26eaeSHeejin Ahn // TeeReg = COPY DefReg 79583c26eaeSHeejin Ahn // Reg = COPY DefReg 79683c26eaeSHeejin Ahn // INST ..., TeeReg, ... 79783c26eaeSHeejin Ahn // INST ..., Reg, ... 79883c26eaeSHeejin Ahn // INST ..., Reg, ... 79983c26eaeSHeejin Ahn for (auto I = MBB.begin(), E = MBB.end(); I != E;) { 80083c26eaeSHeejin Ahn MachineInstr &MI = *I++; 80183c26eaeSHeejin Ahn if (!WebAssembly::isTee(MI.getOpcode())) 80283c26eaeSHeejin Ahn continue; 80383c26eaeSHeejin Ahn Register TeeReg = MI.getOperand(0).getReg(); 80483c26eaeSHeejin Ahn Register Reg = MI.getOperand(1).getReg(); 80583c26eaeSHeejin Ahn Register DefReg = MI.getOperand(2).getReg(); 80683c26eaeSHeejin Ahn if (!MFI.isVRegStackified(TeeReg)) { 80783c26eaeSHeejin Ahn // Now we are not using TEE anymore, so unstackify DefReg too 80883c26eaeSHeejin Ahn MFI.unstackifyVReg(DefReg); 80983c26eaeSHeejin Ahn unsigned CopyOpc = getCopyOpcode(MRI.getRegClass(DefReg)); 81083c26eaeSHeejin Ahn BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), TeeReg) 81183c26eaeSHeejin Ahn .addReg(DefReg); 81283c26eaeSHeejin Ahn BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), Reg).addReg(DefReg); 81383c26eaeSHeejin Ahn MI.eraseFromParent(); 81483c26eaeSHeejin Ahn } 81583c26eaeSHeejin Ahn } 81661d5c76aSHeejin Ahn } 81761d5c76aSHeejin Ahn 818c4ac74fbSHeejin Ahn bool WebAssemblyCFGStackify::fixUnwindMismatches(MachineFunction &MF) { 819c4ac74fbSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 82061d5c76aSHeejin Ahn auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 821c4ac74fbSHeejin Ahn MachineRegisterInfo &MRI = MF.getRegInfo(); 822c4ac74fbSHeejin Ahn 823c4ac74fbSHeejin Ahn // Linearizing the control flow by placing TRY / END_TRY markers can create 824c4ac74fbSHeejin Ahn // mismatches in unwind destinations. There are two kinds of mismatches we 825c4ac74fbSHeejin Ahn // try to solve here. 826c4ac74fbSHeejin Ahn 827c4ac74fbSHeejin Ahn // 1. When an instruction may throw, but the EH pad it will unwind to can be 828c4ac74fbSHeejin Ahn // different from the original CFG. 829c4ac74fbSHeejin Ahn // 830c4ac74fbSHeejin Ahn // Example: we have the following CFG: 831c4ac74fbSHeejin Ahn // bb0: 832c4ac74fbSHeejin Ahn // call @foo (if it throws, unwind to bb2) 833c4ac74fbSHeejin Ahn // bb1: 834c4ac74fbSHeejin Ahn // call @bar (if it throws, unwind to bb3) 835c4ac74fbSHeejin Ahn // bb2 (ehpad): 836c4ac74fbSHeejin Ahn // catch 837c4ac74fbSHeejin Ahn // ... 838c4ac74fbSHeejin Ahn // bb3 (ehpad) 839c4ac74fbSHeejin Ahn // catch 840c4ac74fbSHeejin Ahn // handler body 841c4ac74fbSHeejin Ahn // 842c4ac74fbSHeejin Ahn // And the CFG is sorted in this order. Then after placing TRY markers, it 843c4ac74fbSHeejin Ahn // will look like: (BB markers are omitted) 844c4ac74fbSHeejin Ahn // try $label1 845c4ac74fbSHeejin Ahn // try 846c4ac74fbSHeejin Ahn // call @foo 847c4ac74fbSHeejin Ahn // call @bar (if it throws, unwind to bb3) 848c4ac74fbSHeejin Ahn // catch <- ehpad (bb2) 849c4ac74fbSHeejin Ahn // ... 850c4ac74fbSHeejin Ahn // end_try 851c4ac74fbSHeejin Ahn // catch <- ehpad (bb3) 852c4ac74fbSHeejin Ahn // handler body 853c4ac74fbSHeejin Ahn // end_try 854c4ac74fbSHeejin Ahn // 855c4ac74fbSHeejin Ahn // Now if bar() throws, it is going to end up ip in bb2, not bb3, where it 856c4ac74fbSHeejin Ahn // is supposed to end up. We solve this problem by 857c4ac74fbSHeejin Ahn // a. Split the target unwind EH pad (here bb3) so that the handler body is 858c4ac74fbSHeejin Ahn // right after 'end_try', which means we extract the handler body out of 859c4ac74fbSHeejin Ahn // the catch block. We do this because this handler body should be 860c4ac74fbSHeejin Ahn // somewhere branch-eable from the inner scope. 861c4ac74fbSHeejin Ahn // b. Wrap the call that has an incorrect unwind destination ('call @bar' 862c4ac74fbSHeejin Ahn // here) with a nested try/catch/end_try scope, and within the new catch 863c4ac74fbSHeejin Ahn // block, branches to the handler body. 864c4ac74fbSHeejin Ahn // c. Place a branch after the newly inserted nested end_try so it can bypass 865c4ac74fbSHeejin Ahn // the handler body, which is now outside of a catch block. 866c4ac74fbSHeejin Ahn // 867c4ac74fbSHeejin Ahn // The result will like as follows. (new: a) means this instruction is newly 868c4ac74fbSHeejin Ahn // created in the process of doing 'a' above. 869c4ac74fbSHeejin Ahn // 870c4ac74fbSHeejin Ahn // block $label0 (new: placeBlockMarker) 871c4ac74fbSHeejin Ahn // try $label1 872c4ac74fbSHeejin Ahn // try 873c4ac74fbSHeejin Ahn // call @foo 874c4ac74fbSHeejin Ahn // try (new: b) 875c4ac74fbSHeejin Ahn // call @bar 876c4ac74fbSHeejin Ahn // catch (new: b) 877c4ac74fbSHeejin Ahn // local.set n / drop (new: b) 878c4ac74fbSHeejin Ahn // br $label1 (new: b) 879c4ac74fbSHeejin Ahn // end_try (new: b) 880c4ac74fbSHeejin Ahn // catch <- ehpad (bb2) 881c4ac74fbSHeejin Ahn // end_try 882c4ac74fbSHeejin Ahn // br $label0 (new: c) 883c4ac74fbSHeejin Ahn // catch <- ehpad (bb3) 884c4ac74fbSHeejin Ahn // end_try (hoisted: a) 885c4ac74fbSHeejin Ahn // handler body 886c4ac74fbSHeejin Ahn // end_block (new: placeBlockMarker) 887c4ac74fbSHeejin Ahn // 888c4ac74fbSHeejin Ahn // Note that the new wrapping block/end_block will be generated later in 889c4ac74fbSHeejin Ahn // placeBlockMarker. 890c4ac74fbSHeejin Ahn // 8919f96a58cSHeejin Ahn // TODO Currently local.set and local.gets are generated to move exnref value 8929f96a58cSHeejin Ahn // created by catches. That's because we don't support yielding values from a 8939f96a58cSHeejin Ahn // block in LLVM machine IR yet, even though it is supported by wasm. Delete 8949f96a58cSHeejin Ahn // unnecessary local.get/local.sets once yielding values from a block is 8959f96a58cSHeejin Ahn // supported. The full EH spec requires multi-value support to do this, but 896c4ac74fbSHeejin Ahn // for C++ we don't yet need it because we only throw a single i32. 897c4ac74fbSHeejin Ahn // 898c4ac74fbSHeejin Ahn // --- 899c4ac74fbSHeejin Ahn // 2. The same as 1, but in this case an instruction unwinds to a caller 900c4ac74fbSHeejin Ahn // function and not another EH pad. 901c4ac74fbSHeejin Ahn // 902c4ac74fbSHeejin Ahn // Example: we have the following CFG: 903c4ac74fbSHeejin Ahn // bb0: 904c4ac74fbSHeejin Ahn // call @foo (if it throws, unwind to bb2) 905c4ac74fbSHeejin Ahn // bb1: 906c4ac74fbSHeejin Ahn // call @bar (if it throws, unwind to caller) 907c4ac74fbSHeejin Ahn // bb2 (ehpad): 908c4ac74fbSHeejin Ahn // catch 909c4ac74fbSHeejin Ahn // ... 910c4ac74fbSHeejin Ahn // 911c4ac74fbSHeejin Ahn // And the CFG is sorted in this order. Then after placing TRY markers, it 912c4ac74fbSHeejin Ahn // will look like: 913c4ac74fbSHeejin Ahn // try 914c4ac74fbSHeejin Ahn // call @foo 915c4ac74fbSHeejin Ahn // call @bar (if it throws, unwind to caller) 916c4ac74fbSHeejin Ahn // catch <- ehpad (bb2) 917c4ac74fbSHeejin Ahn // ... 918c4ac74fbSHeejin Ahn // end_try 919c4ac74fbSHeejin Ahn // 920c4ac74fbSHeejin Ahn // Now if bar() throws, it is going to end up ip in bb2, when it is supposed 921c4ac74fbSHeejin Ahn // throw up to the caller. 922c4ac74fbSHeejin Ahn // We solve this problem by 923c4ac74fbSHeejin Ahn // a. Create a new 'appendix' BB at the end of the function and put a single 924c4ac74fbSHeejin Ahn // 'rethrow' instruction (+ local.get) in there. 925c4ac74fbSHeejin Ahn // b. Wrap the call that has an incorrect unwind destination ('call @bar' 926c4ac74fbSHeejin Ahn // here) with a nested try/catch/end_try scope, and within the new catch 927c4ac74fbSHeejin Ahn // block, branches to the new appendix block. 928c4ac74fbSHeejin Ahn // 929c4ac74fbSHeejin Ahn // block $label0 (new: placeBlockMarker) 930c4ac74fbSHeejin Ahn // try 931c4ac74fbSHeejin Ahn // call @foo 932c4ac74fbSHeejin Ahn // try (new: b) 933c4ac74fbSHeejin Ahn // call @bar 934c4ac74fbSHeejin Ahn // catch (new: b) 935c4ac74fbSHeejin Ahn // local.set n (new: b) 936c4ac74fbSHeejin Ahn // br $label0 (new: b) 937c4ac74fbSHeejin Ahn // end_try (new: b) 938c4ac74fbSHeejin Ahn // catch <- ehpad (bb2) 939c4ac74fbSHeejin Ahn // ... 940c4ac74fbSHeejin Ahn // end_try 941c4ac74fbSHeejin Ahn // ... 942c4ac74fbSHeejin Ahn // end_block (new: placeBlockMarker) 943c4ac74fbSHeejin Ahn // local.get n (new: a) <- appendix block 944c4ac74fbSHeejin Ahn // rethrow (new: a) 945c4ac74fbSHeejin Ahn // 946c4ac74fbSHeejin Ahn // In case there are multiple calls in a BB that may throw to the caller, they 947c4ac74fbSHeejin Ahn // can be wrapped together in one nested try scope. (In 1, this couldn't 948c4ac74fbSHeejin Ahn // happen, because may-throwing instruction there had an unwind destination, 949c4ac74fbSHeejin Ahn // i.e., it was an invoke before, and there could be only one invoke within a 950c4ac74fbSHeejin Ahn // BB.) 951c4ac74fbSHeejin Ahn 952c4ac74fbSHeejin Ahn SmallVector<const MachineBasicBlock *, 8> EHPadStack; 953c4ac74fbSHeejin Ahn // Range of intructions to be wrapped in a new nested try/catch 954c4ac74fbSHeejin Ahn using TryRange = std::pair<MachineInstr *, MachineInstr *>; 955daeead4bSHeejin Ahn // In original CFG, <unwind destination BB, a vector of try ranges> 956c4ac74fbSHeejin Ahn DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> UnwindDestToTryRanges; 957c4ac74fbSHeejin Ahn // In new CFG, <destination to branch to, a vector of try ranges> 958c4ac74fbSHeejin Ahn DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> BrDestToTryRanges; 9599f96a58cSHeejin Ahn // In new CFG, <destination to branch to, register containing exnref> 960c4ac74fbSHeejin Ahn DenseMap<MachineBasicBlock *, unsigned> BrDestToExnReg; 961c4ac74fbSHeejin Ahn 962834debffSHeejin Ahn // Destinations for branches that will be newly added, for which a new 963834debffSHeejin Ahn // BLOCK/END_BLOCK markers are necessary. 964834debffSHeejin Ahn SmallVector<MachineBasicBlock *, 8> BrDests; 965834debffSHeejin Ahn 966c4ac74fbSHeejin Ahn // Gather possibly throwing calls (i.e., previously invokes) whose current 967c4ac74fbSHeejin Ahn // unwind destination is not the same as the original CFG. 968c4ac74fbSHeejin Ahn for (auto &MBB : reverse(MF)) { 969c4ac74fbSHeejin Ahn bool SeenThrowableInstInBB = false; 970c4ac74fbSHeejin Ahn for (auto &MI : reverse(MBB)) { 971c4ac74fbSHeejin Ahn if (MI.getOpcode() == WebAssembly::TRY) 972c4ac74fbSHeejin Ahn EHPadStack.pop_back(); 973c4ac74fbSHeejin Ahn else if (MI.getOpcode() == WebAssembly::CATCH) 974c4ac74fbSHeejin Ahn EHPadStack.push_back(MI.getParent()); 975c4ac74fbSHeejin Ahn 976c4ac74fbSHeejin Ahn // In this loop we only gather calls that have an EH pad to unwind. So 977c4ac74fbSHeejin Ahn // there will be at most 1 such call (= invoke) in a BB, so after we've 978c4ac74fbSHeejin Ahn // seen one, we can skip the rest of BB. Also if MBB has no EH pad 979c4ac74fbSHeejin Ahn // successor or MI does not throw, this is not an invoke. 980c4ac74fbSHeejin Ahn if (SeenThrowableInstInBB || !MBB.hasEHPadSuccessor() || 981c4ac74fbSHeejin Ahn !WebAssembly::mayThrow(MI)) 982c4ac74fbSHeejin Ahn continue; 983c4ac74fbSHeejin Ahn SeenThrowableInstInBB = true; 984c4ac74fbSHeejin Ahn 985c4ac74fbSHeejin Ahn // If the EH pad on the stack top is where this instruction should unwind 986c4ac74fbSHeejin Ahn // next, we're good. 987c4ac74fbSHeejin Ahn MachineBasicBlock *UnwindDest = nullptr; 988c4ac74fbSHeejin Ahn for (auto *Succ : MBB.successors()) { 989c4ac74fbSHeejin Ahn if (Succ->isEHPad()) { 990c4ac74fbSHeejin Ahn UnwindDest = Succ; 991c4ac74fbSHeejin Ahn break; 992c4ac74fbSHeejin Ahn } 993c4ac74fbSHeejin Ahn } 994c4ac74fbSHeejin Ahn if (EHPadStack.back() == UnwindDest) 995c4ac74fbSHeejin Ahn continue; 996c4ac74fbSHeejin Ahn 997c4ac74fbSHeejin Ahn // If not, record the range. 998c4ac74fbSHeejin Ahn UnwindDestToTryRanges[UnwindDest].push_back(TryRange(&MI, &MI)); 999c4ac74fbSHeejin Ahn } 1000c4ac74fbSHeejin Ahn } 1001c4ac74fbSHeejin Ahn 1002c4ac74fbSHeejin Ahn assert(EHPadStack.empty()); 1003c4ac74fbSHeejin Ahn 1004c4ac74fbSHeejin Ahn // Gather possibly throwing calls that are supposed to unwind up to the caller 1005c4ac74fbSHeejin Ahn // if they throw, but currently unwind to an incorrect destination. Unlike the 1006c4ac74fbSHeejin Ahn // loop above, there can be multiple calls within a BB that unwind to the 1007c4ac74fbSHeejin Ahn // caller, which we should group together in a range. 1008c4ac74fbSHeejin Ahn bool NeedAppendixBlock = false; 1009c4ac74fbSHeejin Ahn for (auto &MBB : reverse(MF)) { 1010c4ac74fbSHeejin Ahn MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; // inclusive 1011c4ac74fbSHeejin Ahn for (auto &MI : reverse(MBB)) { 1012c4ac74fbSHeejin Ahn if (MI.getOpcode() == WebAssembly::TRY) 1013c4ac74fbSHeejin Ahn EHPadStack.pop_back(); 1014c4ac74fbSHeejin Ahn else if (MI.getOpcode() == WebAssembly::CATCH) 1015c4ac74fbSHeejin Ahn EHPadStack.push_back(MI.getParent()); 1016c4ac74fbSHeejin Ahn 1017c4ac74fbSHeejin Ahn // If MBB has an EH pad successor, this inst does not unwind to caller. 1018c4ac74fbSHeejin Ahn if (MBB.hasEHPadSuccessor()) 1019c4ac74fbSHeejin Ahn continue; 1020c4ac74fbSHeejin Ahn 1021c4ac74fbSHeejin Ahn // We wrap up the current range when we see a marker even if we haven't 1022c4ac74fbSHeejin Ahn // finished a BB. 1023d8ddf839SWouter van Oortmerssen if (RangeEnd && WebAssembly::isMarker(MI.getOpcode())) { 1024c4ac74fbSHeejin Ahn NeedAppendixBlock = true; 1025c4ac74fbSHeejin Ahn // Record the range. nullptr here means the unwind destination is the 1026c4ac74fbSHeejin Ahn // caller. 1027c4ac74fbSHeejin Ahn UnwindDestToTryRanges[nullptr].push_back( 1028c4ac74fbSHeejin Ahn TryRange(RangeBegin, RangeEnd)); 1029c4ac74fbSHeejin Ahn RangeBegin = RangeEnd = nullptr; // Reset range pointers 1030c4ac74fbSHeejin Ahn } 1031c4ac74fbSHeejin Ahn 1032c4ac74fbSHeejin Ahn // If EHPadStack is empty, that means it is correctly unwind to caller if 1033c4ac74fbSHeejin Ahn // it throws, so we're good. If MI does not throw, we're good too. 1034c4ac74fbSHeejin Ahn if (EHPadStack.empty() || !WebAssembly::mayThrow(MI)) 1035c4ac74fbSHeejin Ahn continue; 1036c4ac74fbSHeejin Ahn 1037c4ac74fbSHeejin Ahn // We found an instruction that unwinds to the caller but currently has an 1038c4ac74fbSHeejin Ahn // incorrect unwind destination. Create a new range or increment the 1039c4ac74fbSHeejin Ahn // currently existing range. 1040c4ac74fbSHeejin Ahn if (!RangeEnd) 1041c4ac74fbSHeejin Ahn RangeBegin = RangeEnd = &MI; 1042c4ac74fbSHeejin Ahn else 1043c4ac74fbSHeejin Ahn RangeBegin = &MI; 1044c4ac74fbSHeejin Ahn } 1045c4ac74fbSHeejin Ahn 1046c4ac74fbSHeejin Ahn if (RangeEnd) { 1047c4ac74fbSHeejin Ahn NeedAppendixBlock = true; 1048c4ac74fbSHeejin Ahn // Record the range. nullptr here means the unwind destination is the 1049c4ac74fbSHeejin Ahn // caller. 1050c4ac74fbSHeejin Ahn UnwindDestToTryRanges[nullptr].push_back(TryRange(RangeBegin, RangeEnd)); 1051c4ac74fbSHeejin Ahn RangeBegin = RangeEnd = nullptr; // Reset range pointers 1052c4ac74fbSHeejin Ahn } 1053c4ac74fbSHeejin Ahn } 1054c4ac74fbSHeejin Ahn 1055c4ac74fbSHeejin Ahn assert(EHPadStack.empty()); 1056c4ac74fbSHeejin Ahn // We don't have any unwind destination mismatches to resolve. 1057c4ac74fbSHeejin Ahn if (UnwindDestToTryRanges.empty()) 1058c4ac74fbSHeejin Ahn return false; 1059c4ac74fbSHeejin Ahn 1060c4ac74fbSHeejin Ahn // If we found instructions that should unwind to the caller but currently 1061c4ac74fbSHeejin Ahn // have incorrect unwind destination, we create an appendix block at the end 1062c4ac74fbSHeejin Ahn // of the function with a local.get and a rethrow instruction. 1063c4ac74fbSHeejin Ahn if (NeedAppendixBlock) { 1064c4ac74fbSHeejin Ahn auto *AppendixBB = getAppendixBlock(MF); 106505c145d6SDaniel Sanders Register ExnReg = MRI.createVirtualRegister(&WebAssembly::EXNREFRegClass); 1066c4ac74fbSHeejin Ahn BuildMI(AppendixBB, DebugLoc(), TII.get(WebAssembly::RETHROW)) 1067c4ac74fbSHeejin Ahn .addReg(ExnReg); 1068c4ac74fbSHeejin Ahn // These instruction ranges should branch to this appendix BB. 1069c4ac74fbSHeejin Ahn for (auto Range : UnwindDestToTryRanges[nullptr]) 1070c4ac74fbSHeejin Ahn BrDestToTryRanges[AppendixBB].push_back(Range); 1071c4ac74fbSHeejin Ahn BrDestToExnReg[AppendixBB] = ExnReg; 1072c4ac74fbSHeejin Ahn } 1073c4ac74fbSHeejin Ahn 1074c4ac74fbSHeejin Ahn // We loop through unwind destination EH pads that are targeted from some 1075c4ac74fbSHeejin Ahn // inner scopes. Because these EH pads are destination of more than one scope 1076c4ac74fbSHeejin Ahn // now, we split them so that the handler body is after 'end_try'. 1077c4ac74fbSHeejin Ahn // - Before 1078c4ac74fbSHeejin Ahn // ehpad: 1079c4ac74fbSHeejin Ahn // catch 1080c4ac74fbSHeejin Ahn // local.set n / drop 1081c4ac74fbSHeejin Ahn // handler body 1082c4ac74fbSHeejin Ahn // ... 1083c4ac74fbSHeejin Ahn // cont: 1084c4ac74fbSHeejin Ahn // end_try 1085c4ac74fbSHeejin Ahn // 1086c4ac74fbSHeejin Ahn // - After 1087c4ac74fbSHeejin Ahn // ehpad: 1088c4ac74fbSHeejin Ahn // catch 1089c4ac74fbSHeejin Ahn // local.set n / drop 1090c4ac74fbSHeejin Ahn // brdest: (new) 1091c4ac74fbSHeejin Ahn // end_try (hoisted from 'cont' BB) 1092c4ac74fbSHeejin Ahn // handler body (taken from 'ehpad') 1093c4ac74fbSHeejin Ahn // ... 1094c4ac74fbSHeejin Ahn // cont: 1095c4ac74fbSHeejin Ahn for (auto &P : UnwindDestToTryRanges) { 1096daeead4bSHeejin Ahn NumUnwindMismatches += P.second.size(); 1097c4ac74fbSHeejin Ahn 1098c4ac74fbSHeejin Ahn // This means the destination is the appendix BB, which was separately 1099c4ac74fbSHeejin Ahn // handled above. 1100c4ac74fbSHeejin Ahn if (!P.first) 1101c4ac74fbSHeejin Ahn continue; 1102c4ac74fbSHeejin Ahn 1103c4ac74fbSHeejin Ahn MachineBasicBlock *EHPad = P.first; 1104c4ac74fbSHeejin Ahn 1105c4ac74fbSHeejin Ahn // Find 'catch' and 'local.set' or 'drop' instruction that follows the 1106c4ac74fbSHeejin Ahn // 'catch'. If -wasm-disable-explicit-locals is not set, 'catch' should be 1107c4ac74fbSHeejin Ahn // always followed by either 'local.set' or a 'drop', because 'br_on_exn' is 1108c4ac74fbSHeejin Ahn // generated after 'catch' in LateEHPrepare and we don't support blocks 1109c4ac74fbSHeejin Ahn // taking values yet. 1110c4ac74fbSHeejin Ahn MachineInstr *Catch = nullptr; 1111c4ac74fbSHeejin Ahn unsigned ExnReg = 0; 1112c4ac74fbSHeejin Ahn for (auto &MI : *EHPad) { 1113c4ac74fbSHeejin Ahn switch (MI.getOpcode()) { 1114c4ac74fbSHeejin Ahn case WebAssembly::CATCH: 1115c4ac74fbSHeejin Ahn Catch = &MI; 1116c4ac74fbSHeejin Ahn ExnReg = Catch->getOperand(0).getReg(); 1117c4ac74fbSHeejin Ahn break; 1118c4ac74fbSHeejin Ahn } 1119c4ac74fbSHeejin Ahn } 1120c4ac74fbSHeejin Ahn assert(Catch && "EH pad does not have a catch"); 1121c4ac74fbSHeejin Ahn assert(ExnReg != 0 && "Invalid register"); 1122c4ac74fbSHeejin Ahn 1123c4ac74fbSHeejin Ahn auto SplitPos = std::next(Catch->getIterator()); 1124c4ac74fbSHeejin Ahn 1125c4ac74fbSHeejin Ahn // Create a new BB that's gonna be the destination for branches from the 1126c4ac74fbSHeejin Ahn // inner mismatched scope. 1127c4ac74fbSHeejin Ahn MachineInstr *BeginTry = EHPadToTry[EHPad]; 1128c4ac74fbSHeejin Ahn MachineInstr *EndTry = BeginToEnd[BeginTry]; 1129c4ac74fbSHeejin Ahn MachineBasicBlock *Cont = EndTry->getParent(); 1130c4ac74fbSHeejin Ahn auto *BrDest = MF.CreateMachineBasicBlock(); 1131c4ac74fbSHeejin Ahn MF.insert(std::next(EHPad->getIterator()), BrDest); 1132c4ac74fbSHeejin Ahn // Hoist up the existing 'end_try'. 1133c4ac74fbSHeejin Ahn BrDest->insert(BrDest->end(), EndTry->removeFromParent()); 1134c4ac74fbSHeejin Ahn // Take out the handler body from EH pad to the new branch destination BB. 1135c4ac74fbSHeejin Ahn BrDest->splice(BrDest->end(), EHPad, SplitPos, EHPad->end()); 113683c26eaeSHeejin Ahn unstackifyVRegsUsedInSplitBB(*EHPad, *BrDest, MFI, MRI, TII); 1137c4ac74fbSHeejin Ahn // Fix predecessor-successor relationship. 1138c4ac74fbSHeejin Ahn BrDest->transferSuccessors(EHPad); 1139c4ac74fbSHeejin Ahn EHPad->addSuccessor(BrDest); 1140c4ac74fbSHeejin Ahn 1141c4ac74fbSHeejin Ahn // All try ranges that were supposed to unwind to this EH pad now have to 1142c4ac74fbSHeejin Ahn // branch to this new branch dest BB. 1143c4ac74fbSHeejin Ahn for (auto Range : UnwindDestToTryRanges[EHPad]) 1144c4ac74fbSHeejin Ahn BrDestToTryRanges[BrDest].push_back(Range); 1145c4ac74fbSHeejin Ahn BrDestToExnReg[BrDest] = ExnReg; 1146c4ac74fbSHeejin Ahn 1147c4ac74fbSHeejin Ahn // In case we fall through to the continuation BB after the catch block, we 1148c4ac74fbSHeejin Ahn // now have to add a branch to it. 1149c4ac74fbSHeejin Ahn // - Before 1150c4ac74fbSHeejin Ahn // try 1151c4ac74fbSHeejin Ahn // ... 1152c4ac74fbSHeejin Ahn // (falls through to 'cont') 1153c4ac74fbSHeejin Ahn // catch 1154c4ac74fbSHeejin Ahn // handler body 1155c4ac74fbSHeejin Ahn // end 1156c4ac74fbSHeejin Ahn // <-- cont 1157c4ac74fbSHeejin Ahn // 1158c4ac74fbSHeejin Ahn // - After 1159c4ac74fbSHeejin Ahn // try 1160c4ac74fbSHeejin Ahn // ... 1161c4ac74fbSHeejin Ahn // br %cont (new) 1162c4ac74fbSHeejin Ahn // catch 1163c4ac74fbSHeejin Ahn // end 1164c4ac74fbSHeejin Ahn // handler body 1165c4ac74fbSHeejin Ahn // <-- cont 1166c4ac74fbSHeejin Ahn MachineBasicBlock *EHPadLayoutPred = &*std::prev(EHPad->getIterator()); 1167c4ac74fbSHeejin Ahn MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 1168c4ac74fbSHeejin Ahn SmallVector<MachineOperand, 4> Cond; 1169c4ac74fbSHeejin Ahn bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond); 1170c4ac74fbSHeejin Ahn if (Analyzable && !TBB && !FBB) { 1171c4ac74fbSHeejin Ahn DebugLoc DL = EHPadLayoutPred->empty() 1172c4ac74fbSHeejin Ahn ? DebugLoc() 1173c4ac74fbSHeejin Ahn : EHPadLayoutPred->rbegin()->getDebugLoc(); 1174c4ac74fbSHeejin Ahn BuildMI(EHPadLayoutPred, DL, TII.get(WebAssembly::BR)).addMBB(Cont); 1175834debffSHeejin Ahn BrDests.push_back(Cont); 1176c4ac74fbSHeejin Ahn } 1177c4ac74fbSHeejin Ahn } 1178c4ac74fbSHeejin Ahn 1179c4ac74fbSHeejin Ahn // For possibly throwing calls whose unwind destinations are currently 1180c4ac74fbSHeejin Ahn // incorrect because of CFG linearization, we wrap them with a nested 1181c4ac74fbSHeejin Ahn // try/catch/end_try, and within the new catch block, we branch to the correct 1182c4ac74fbSHeejin Ahn // handler. 1183c4ac74fbSHeejin Ahn // - Before 1184c4ac74fbSHeejin Ahn // mbb: 1185c4ac74fbSHeejin Ahn // call @foo <- Unwind destination mismatch! 1186c4ac74fbSHeejin Ahn // ehpad: 1187c4ac74fbSHeejin Ahn // ... 1188c4ac74fbSHeejin Ahn // 1189c4ac74fbSHeejin Ahn // - After 1190c4ac74fbSHeejin Ahn // mbb: 1191c4ac74fbSHeejin Ahn // try (new) 1192c4ac74fbSHeejin Ahn // call @foo 1193c4ac74fbSHeejin Ahn // nested-ehpad: (new) 1194c4ac74fbSHeejin Ahn // catch (new) 1195c4ac74fbSHeejin Ahn // local.set n / drop (new) 1196c4ac74fbSHeejin Ahn // br %brdest (new) 1197c4ac74fbSHeejin Ahn // nested-end: (new) 1198c4ac74fbSHeejin Ahn // end_try (new) 1199c4ac74fbSHeejin Ahn // ehpad: 1200c4ac74fbSHeejin Ahn // ... 1201c4ac74fbSHeejin Ahn for (auto &P : BrDestToTryRanges) { 1202c4ac74fbSHeejin Ahn MachineBasicBlock *BrDest = P.first; 1203c4ac74fbSHeejin Ahn auto &TryRanges = P.second; 1204c4ac74fbSHeejin Ahn unsigned ExnReg = BrDestToExnReg[BrDest]; 1205c4ac74fbSHeejin Ahn 1206c4ac74fbSHeejin Ahn for (auto Range : TryRanges) { 1207c4ac74fbSHeejin Ahn MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; 1208c4ac74fbSHeejin Ahn std::tie(RangeBegin, RangeEnd) = Range; 1209c4ac74fbSHeejin Ahn auto *MBB = RangeBegin->getParent(); 1210ba40896fSHeejin Ahn // Store the first function call from this range, because RangeBegin can 1211ba40896fSHeejin Ahn // be moved to point EH_LABEL before the call 1212ba40896fSHeejin Ahn MachineInstr *RangeBeginCall = RangeBegin; 1213c4ac74fbSHeejin Ahn 1214c4ac74fbSHeejin Ahn // Include possible EH_LABELs in the range 1215c4ac74fbSHeejin Ahn if (RangeBegin->getIterator() != MBB->begin() && 1216c4ac74fbSHeejin Ahn std::prev(RangeBegin->getIterator())->isEHLabel()) 1217c4ac74fbSHeejin Ahn RangeBegin = &*std::prev(RangeBegin->getIterator()); 1218c4ac74fbSHeejin Ahn if (std::next(RangeEnd->getIterator()) != MBB->end() && 1219c4ac74fbSHeejin Ahn std::next(RangeEnd->getIterator())->isEHLabel()) 1220c4ac74fbSHeejin Ahn RangeEnd = &*std::next(RangeEnd->getIterator()); 1221c4ac74fbSHeejin Ahn 1222c4ac74fbSHeejin Ahn MachineBasicBlock *EHPad = nullptr; 1223c4ac74fbSHeejin Ahn for (auto *Succ : MBB->successors()) { 1224c4ac74fbSHeejin Ahn if (Succ->isEHPad()) { 1225c4ac74fbSHeejin Ahn EHPad = Succ; 1226c4ac74fbSHeejin Ahn break; 1227c4ac74fbSHeejin Ahn } 1228c4ac74fbSHeejin Ahn } 1229c4ac74fbSHeejin Ahn 1230ba40896fSHeejin Ahn // Local expression tree before the first call of this range should go 1231ba40896fSHeejin Ahn // after the nested TRY. 1232ba40896fSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 1233ba40896fSHeejin Ahn AfterSet.insert(RangeBegin); 1234ba40896fSHeejin Ahn AfterSet.insert(RangeBeginCall); 1235ba40896fSHeejin Ahn for (auto I = MachineBasicBlock::iterator(RangeBeginCall), 1236ba40896fSHeejin Ahn E = MBB->begin(); 1237ba40896fSHeejin Ahn I != E; --I) { 1238ba40896fSHeejin Ahn if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 1239ba40896fSHeejin Ahn continue; 1240ba40896fSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI)) 1241ba40896fSHeejin Ahn AfterSet.insert(&*std::prev(I)); 1242ba40896fSHeejin Ahn else 1243ba40896fSHeejin Ahn break; 1244ba40896fSHeejin Ahn } 1245ba40896fSHeejin Ahn 1246c4ac74fbSHeejin Ahn // Create the nested try instruction. 1247ba40896fSHeejin Ahn auto InsertPos = getLatestInsertPos( 1248ba40896fSHeejin Ahn MBB, SmallPtrSet<const MachineInstr *, 4>(), AfterSet); 1249c4ac74fbSHeejin Ahn MachineInstr *NestedTry = 1250ba40896fSHeejin Ahn BuildMI(*MBB, InsertPos, RangeBegin->getDebugLoc(), 1251c4ac74fbSHeejin Ahn TII.get(WebAssembly::TRY)) 12522cb27072SThomas Lively .addImm(int64_t(WebAssembly::BlockType::Void)); 1253c4ac74fbSHeejin Ahn 1254c4ac74fbSHeejin Ahn // Create the nested EH pad and fill instructions in. 1255c4ac74fbSHeejin Ahn MachineBasicBlock *NestedEHPad = MF.CreateMachineBasicBlock(); 1256c4ac74fbSHeejin Ahn MF.insert(std::next(MBB->getIterator()), NestedEHPad); 1257c4ac74fbSHeejin Ahn NestedEHPad->setIsEHPad(); 1258c4ac74fbSHeejin Ahn NestedEHPad->setIsEHScopeEntry(); 1259c4ac74fbSHeejin Ahn BuildMI(NestedEHPad, RangeEnd->getDebugLoc(), TII.get(WebAssembly::CATCH), 1260c4ac74fbSHeejin Ahn ExnReg); 1261c4ac74fbSHeejin Ahn BuildMI(NestedEHPad, RangeEnd->getDebugLoc(), TII.get(WebAssembly::BR)) 1262c4ac74fbSHeejin Ahn .addMBB(BrDest); 1263c4ac74fbSHeejin Ahn 1264c4ac74fbSHeejin Ahn // Create the nested continuation BB and end_try instruction. 1265c4ac74fbSHeejin Ahn MachineBasicBlock *NestedCont = MF.CreateMachineBasicBlock(); 1266c4ac74fbSHeejin Ahn MF.insert(std::next(NestedEHPad->getIterator()), NestedCont); 1267c4ac74fbSHeejin Ahn MachineInstr *NestedEndTry = 1268c4ac74fbSHeejin Ahn BuildMI(*NestedCont, NestedCont->begin(), RangeEnd->getDebugLoc(), 1269c4ac74fbSHeejin Ahn TII.get(WebAssembly::END_TRY)); 1270c4ac74fbSHeejin Ahn // In case MBB has more instructions after the try range, move them to the 1271c4ac74fbSHeejin Ahn // new nested continuation BB. 1272c4ac74fbSHeejin Ahn NestedCont->splice(NestedCont->end(), MBB, 1273c4ac74fbSHeejin Ahn std::next(RangeEnd->getIterator()), MBB->end()); 127483c26eaeSHeejin Ahn unstackifyVRegsUsedInSplitBB(*MBB, *NestedCont, MFI, MRI, TII); 1275c4ac74fbSHeejin Ahn registerTryScope(NestedTry, NestedEndTry, NestedEHPad); 1276c4ac74fbSHeejin Ahn 1277c4ac74fbSHeejin Ahn // Fix predecessor-successor relationship. 1278c4ac74fbSHeejin Ahn NestedCont->transferSuccessors(MBB); 1279834debffSHeejin Ahn if (EHPad) { 1280c4ac74fbSHeejin Ahn NestedCont->removeSuccessor(EHPad); 1281834debffSHeejin Ahn // If EHPad does not have any predecessors left after removing 1282834debffSHeejin Ahn // NextedCont predecessor, remove its successor too, because this EHPad 1283834debffSHeejin Ahn // is not reachable from the entry BB anyway. We can't remove EHPad BB 1284834debffSHeejin Ahn // itself because it can contain 'catch' or 'end', which are necessary 1285834debffSHeejin Ahn // for keeping try-catch-end structure. 1286834debffSHeejin Ahn if (EHPad->pred_empty()) 1287834debffSHeejin Ahn EHPad->removeSuccessor(BrDest); 1288834debffSHeejin Ahn } 1289c4ac74fbSHeejin Ahn MBB->addSuccessor(NestedEHPad); 1290c4ac74fbSHeejin Ahn MBB->addSuccessor(NestedCont); 1291c4ac74fbSHeejin Ahn NestedEHPad->addSuccessor(BrDest); 1292c4ac74fbSHeejin Ahn } 1293c4ac74fbSHeejin Ahn } 1294c4ac74fbSHeejin Ahn 1295c4ac74fbSHeejin Ahn // Renumber BBs and recalculate ScopeTop info because new BBs might have been 1296c4ac74fbSHeejin Ahn // created and inserted above. 1297c4ac74fbSHeejin Ahn MF.RenumberBlocks(); 1298c4ac74fbSHeejin Ahn ScopeTops.clear(); 1299c4ac74fbSHeejin Ahn ScopeTops.resize(MF.getNumBlockIDs()); 1300c4ac74fbSHeejin Ahn for (auto &MBB : reverse(MF)) { 1301c4ac74fbSHeejin Ahn for (auto &MI : reverse(MBB)) { 1302c4ac74fbSHeejin Ahn if (ScopeTops[MBB.getNumber()]) 1303c4ac74fbSHeejin Ahn break; 1304c4ac74fbSHeejin Ahn switch (MI.getOpcode()) { 1305c4ac74fbSHeejin Ahn case WebAssembly::END_BLOCK: 1306c4ac74fbSHeejin Ahn case WebAssembly::END_LOOP: 1307c4ac74fbSHeejin Ahn case WebAssembly::END_TRY: 1308c4ac74fbSHeejin Ahn ScopeTops[MBB.getNumber()] = EndToBegin[&MI]->getParent(); 1309c4ac74fbSHeejin Ahn break; 1310c4ac74fbSHeejin Ahn case WebAssembly::CATCH: 1311c4ac74fbSHeejin Ahn ScopeTops[MBB.getNumber()] = EHPadToTry[&MBB]->getParent(); 1312c4ac74fbSHeejin Ahn break; 1313c4ac74fbSHeejin Ahn } 1314c4ac74fbSHeejin Ahn } 1315c4ac74fbSHeejin Ahn } 1316c4ac74fbSHeejin Ahn 1317c4ac74fbSHeejin Ahn // Recompute the dominator tree. 1318c4ac74fbSHeejin Ahn getAnalysis<MachineDominatorTree>().runOnMachineFunction(MF); 1319c4ac74fbSHeejin Ahn 1320834debffSHeejin Ahn // Place block markers for newly added branches, if necessary. 1321834debffSHeejin Ahn 1322834debffSHeejin Ahn // If we've created an appendix BB and a branch to it, place a block/end_block 1323834debffSHeejin Ahn // marker for that. For some new branches, those branch destination BBs start 1324834debffSHeejin Ahn // with a hoisted end_try marker, so we don't need a new marker there. 1325834debffSHeejin Ahn if (AppendixBB) 1326834debffSHeejin Ahn BrDests.push_back(AppendixBB); 1327834debffSHeejin Ahn 1328c4ac74fbSHeejin Ahn llvm::sort(BrDests, 1329c4ac74fbSHeejin Ahn [&](const MachineBasicBlock *A, const MachineBasicBlock *B) { 1330c4ac74fbSHeejin Ahn auto ANum = A->getNumber(); 1331c4ac74fbSHeejin Ahn auto BNum = B->getNumber(); 1332c4ac74fbSHeejin Ahn return ANum < BNum; 1333c4ac74fbSHeejin Ahn }); 1334c4ac74fbSHeejin Ahn for (auto *Dest : BrDests) 1335c4ac74fbSHeejin Ahn placeBlockMarker(*Dest); 1336c4ac74fbSHeejin Ahn 1337c4ac74fbSHeejin Ahn return true; 1338c4ac74fbSHeejin Ahn } 1339c4ac74fbSHeejin Ahn 13401d68e80fSDan Gohman static unsigned 134118c56a07SHeejin Ahn getDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack, 13421d68e80fSDan Gohman const MachineBasicBlock *MBB) { 13431d68e80fSDan Gohman unsigned Depth = 0; 13441d68e80fSDan Gohman for (auto X : reverse(Stack)) { 13451d68e80fSDan Gohman if (X == MBB) 13461d68e80fSDan Gohman break; 13471d68e80fSDan Gohman ++Depth; 13481d68e80fSDan Gohman } 13491d68e80fSDan Gohman assert(Depth < Stack.size() && "Branch destination should be in scope"); 13501d68e80fSDan Gohman return Depth; 13511d68e80fSDan Gohman } 13521d68e80fSDan Gohman 13532726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable, 13542726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar, 13552726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of 13562726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks 13572726b88cSDan Gohman /// that end at the function end need to have a return type signature that 13582726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function 13592726b88cSDan Gohman /// checks for such cases and fixes up the signatures. 1360e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) { 1361e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 13622726b88cSDan Gohman 13632726b88cSDan Gohman if (MFI.getResults().empty()) 13642726b88cSDan Gohman return; 13652726b88cSDan Gohman 13662cb27072SThomas Lively // MCInstLower will add the proper types to multivalue signatures based on the 13672cb27072SThomas Lively // function return type 13682cb27072SThomas Lively WebAssembly::BlockType RetType = 13692cb27072SThomas Lively MFI.getResults().size() > 1 13702cb27072SThomas Lively ? WebAssembly::BlockType::Multivalue 13712cb27072SThomas Lively : WebAssembly::BlockType( 13722cb27072SThomas Lively WebAssembly::toValType(MFI.getResults().front())); 13732726b88cSDan Gohman 13742726b88cSDan Gohman for (MachineBasicBlock &MBB : reverse(MF)) { 13752726b88cSDan Gohman for (MachineInstr &MI : reverse(MBB)) { 1376801bf7ebSShiva Chen if (MI.isPosition() || MI.isDebugInstr()) 13772726b88cSDan Gohman continue; 13782cb27072SThomas Lively switch (MI.getOpcode()) { 13792cb27072SThomas Lively case WebAssembly::END_BLOCK: 13802cb27072SThomas Lively case WebAssembly::END_LOOP: 13812cb27072SThomas Lively case WebAssembly::END_TRY: 138218c56a07SHeejin Ahn EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType)); 13832726b88cSDan Gohman continue; 13842cb27072SThomas Lively default: 13852726b88cSDan Gohman // Something other than an `end`. We're done. 13862726b88cSDan Gohman return; 13872726b88cSDan Gohman } 13882726b88cSDan Gohman } 13892726b88cSDan Gohman } 13902cb27072SThomas Lively } 13912726b88cSDan Gohman 1392d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body 1393d934cb88SDan Gohman // were a block. 139418c56a07SHeejin Ahn static void appendEndToFunction(MachineFunction &MF, 1395d934cb88SDan Gohman const WebAssemblyInstrInfo &TII) { 139610b31358SDerek Schuff BuildMI(MF.back(), MF.back().end(), 139710b31358SDerek Schuff MF.back().findPrevDebugLoc(MF.back().end()), 1398d934cb88SDan Gohman TII.get(WebAssembly::END_FUNCTION)); 1399d934cb88SDan Gohman } 1400d934cb88SDan Gohman 1401e76fa9ecSHeejin Ahn /// Insert LOOP/TRY/BLOCK markers at appropriate places. 1402e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) { 1403e76fa9ecSHeejin Ahn // We allocate one more than the number of blocks in the function to 1404e76fa9ecSHeejin Ahn // accommodate for the possible fake block we may insert at the end. 1405e76fa9ecSHeejin Ahn ScopeTops.resize(MF.getNumBlockIDs() + 1); 14068fe7e86bSDan Gohman // Place the LOOP for MBB if MBB is the header of a loop. 1407e76fa9ecSHeejin Ahn for (auto &MBB : MF) 1408e76fa9ecSHeejin Ahn placeLoopMarker(MBB); 140944a5a4b1SHeejin Ahn 1410d6f48786SHeejin Ahn const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo(); 141144a5a4b1SHeejin Ahn for (auto &MBB : MF) { 141244a5a4b1SHeejin Ahn if (MBB.isEHPad()) { 141344a5a4b1SHeejin Ahn // Place the TRY for MBB if MBB is the EH pad of an exception. 1414e76fa9ecSHeejin Ahn if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 1415e76fa9ecSHeejin Ahn MF.getFunction().hasPersonalityFn()) 1416e76fa9ecSHeejin Ahn placeTryMarker(MBB); 141744a5a4b1SHeejin Ahn } else { 141832807932SDan Gohman // Place the BLOCK for MBB if MBB is branched to from above. 1419e76fa9ecSHeejin Ahn placeBlockMarker(MBB); 1420950a13cfSDan Gohman } 142144a5a4b1SHeejin Ahn } 1422c4ac74fbSHeejin Ahn // Fix mismatches in unwind destinations induced by linearizing the code. 1423daeead4bSHeejin Ahn if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 1424daeead4bSHeejin Ahn MF.getFunction().hasPersonalityFn()) 1425c4ac74fbSHeejin Ahn fixUnwindMismatches(MF); 142644a5a4b1SHeejin Ahn } 1427950a13cfSDan Gohman 1428e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) { 14291d68e80fSDan Gohman // Now rewrite references to basic blocks to be depth immediates. 14301d68e80fSDan Gohman SmallVector<const MachineBasicBlock *, 8> Stack; 14311d68e80fSDan Gohman for (auto &MBB : reverse(MF)) { 1432e76fa9ecSHeejin Ahn for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) { 1433e76fa9ecSHeejin Ahn MachineInstr &MI = *I; 14341d68e80fSDan Gohman switch (MI.getOpcode()) { 14351d68e80fSDan Gohman case WebAssembly::BLOCK: 1436e76fa9ecSHeejin Ahn case WebAssembly::TRY: 1437e76fa9ecSHeejin Ahn assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= 1438e76fa9ecSHeejin Ahn MBB.getNumber() && 1439e76fa9ecSHeejin Ahn "Block/try marker should be balanced"); 1440e76fa9ecSHeejin Ahn Stack.pop_back(); 1441e76fa9ecSHeejin Ahn break; 1442e76fa9ecSHeejin Ahn 14431d68e80fSDan Gohman case WebAssembly::LOOP: 14441d68e80fSDan Gohman assert(Stack.back() == &MBB && "Loop top should be balanced"); 14451d68e80fSDan Gohman Stack.pop_back(); 14461d68e80fSDan Gohman break; 1447e76fa9ecSHeejin Ahn 14481d68e80fSDan Gohman case WebAssembly::END_BLOCK: 1449e76fa9ecSHeejin Ahn case WebAssembly::END_TRY: 14501d68e80fSDan Gohman Stack.push_back(&MBB); 14511d68e80fSDan Gohman break; 1452e76fa9ecSHeejin Ahn 14531d68e80fSDan Gohman case WebAssembly::END_LOOP: 1454e76fa9ecSHeejin Ahn Stack.push_back(EndToBegin[&MI]->getParent()); 14551d68e80fSDan Gohman break; 1456e76fa9ecSHeejin Ahn 14571d68e80fSDan Gohman default: 14581d68e80fSDan Gohman if (MI.isTerminator()) { 14591d68e80fSDan Gohman // Rewrite MBB operands to be depth immediates. 14601d68e80fSDan Gohman SmallVector<MachineOperand, 4> Ops(MI.operands()); 14611d68e80fSDan Gohman while (MI.getNumOperands() > 0) 14621d68e80fSDan Gohman MI.RemoveOperand(MI.getNumOperands() - 1); 14631d68e80fSDan Gohman for (auto MO : Ops) { 14641d68e80fSDan Gohman if (MO.isMBB()) 146518c56a07SHeejin Ahn MO = MachineOperand::CreateImm(getDepth(Stack, MO.getMBB())); 14661d68e80fSDan Gohman MI.addOperand(MF, MO); 146732807932SDan Gohman } 14681d68e80fSDan Gohman } 14691d68e80fSDan Gohman break; 14701d68e80fSDan Gohman } 14711d68e80fSDan Gohman } 14721d68e80fSDan Gohman } 14731d68e80fSDan Gohman assert(Stack.empty() && "Control flow should be balanced"); 1474e76fa9ecSHeejin Ahn } 14752726b88cSDan Gohman 1476e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::releaseMemory() { 1477e76fa9ecSHeejin Ahn ScopeTops.clear(); 1478e76fa9ecSHeejin Ahn BeginToEnd.clear(); 1479e76fa9ecSHeejin Ahn EndToBegin.clear(); 1480e76fa9ecSHeejin Ahn TryToEHPad.clear(); 1481e76fa9ecSHeejin Ahn EHPadToTry.clear(); 1482c4ac74fbSHeejin Ahn AppendixBB = nullptr; 14831d68e80fSDan Gohman } 148432807932SDan Gohman 1485950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) { 1486d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n" 1487950a13cfSDan Gohman "********** Function: " 1488950a13cfSDan Gohman << MF.getName() << '\n'); 1489cf699b45SHeejin Ahn const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo(); 1490950a13cfSDan Gohman 1491e76fa9ecSHeejin Ahn releaseMemory(); 1492e76fa9ecSHeejin Ahn 1493e040533eSDan Gohman // Liveness is not tracked for VALUE_STACK physreg. 14949c3bf318SDerek Schuff MF.getRegInfo().invalidateLiveness(); 1495950a13cfSDan Gohman 1496e76fa9ecSHeejin Ahn // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes. 1497e76fa9ecSHeejin Ahn placeMarkers(MF); 1498e76fa9ecSHeejin Ahn 1499c4ac74fbSHeejin Ahn // Remove unnecessary instructions possibly introduced by try/end_trys. 1500cf699b45SHeejin Ahn if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 1501cf699b45SHeejin Ahn MF.getFunction().hasPersonalityFn()) 1502cf699b45SHeejin Ahn removeUnnecessaryInstrs(MF); 1503cf699b45SHeejin Ahn 1504e76fa9ecSHeejin Ahn // Convert MBB operands in terminators to relative depth immediates. 1505e76fa9ecSHeejin Ahn rewriteDepthImmediates(MF); 1506e76fa9ecSHeejin Ahn 1507e76fa9ecSHeejin Ahn // Fix up block/loop/try signatures at the end of the function to conform to 1508e76fa9ecSHeejin Ahn // WebAssembly's rules. 1509e76fa9ecSHeejin Ahn fixEndsAtEndOfFunction(MF); 1510e76fa9ecSHeejin Ahn 1511e76fa9ecSHeejin Ahn // Add an end instruction at the end of the function body. 1512e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 1513e76fa9ecSHeejin Ahn if (!MF.getSubtarget<WebAssemblySubtarget>() 1514e76fa9ecSHeejin Ahn .getTargetTriple() 1515e76fa9ecSHeejin Ahn .isOSBinFormatELF()) 151618c56a07SHeejin Ahn appendEndToFunction(MF, TII); 151732807932SDan Gohman 15181aaa481fSHeejin Ahn MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified(); 1519950a13cfSDan Gohman return true; 1520950a13cfSDan Gohman } 1521