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
240b2bc69bSHeejin Ahn #include "Utils/WebAssemblyTypeUtilities.h"
250b2bc69bSHeejin Ahn #include "Utils/WebAssemblyUtilities.h"
266bda14b3SChandler Carruth #include "WebAssembly.h"
27e76fa9ecSHeejin Ahn #include "WebAssemblyExceptionInfo.h"
28ed0f1138SDan Gohman #include "WebAssemblyMachineFunctionInfo.h"
29276f9e8cSHeejin Ahn #include "WebAssemblySortRegion.h"
30950a13cfSDan Gohman #include "WebAssemblySubtarget.h"
31c4ac74fbSHeejin Ahn #include "llvm/ADT/Statistic.h"
3232807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h"
33950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
34904cd3e0SReid Kleckner #include "llvm/CodeGen/MachineLoopInfo.h"
359f770b36SHeejin Ahn #include "llvm/CodeGen/WasmEHFuncInfo.h"
36e76fa9ecSHeejin Ahn #include "llvm/MC/MCAsmInfo.h"
37fe0006c8SSimon Pilgrim #include "llvm/Target/TargetMachine.h"
38950a13cfSDan Gohman using namespace llvm;
39276f9e8cSHeejin Ahn using WebAssembly::SortRegionInfo;
40950a13cfSDan Gohman
41950a13cfSDan Gohman #define DEBUG_TYPE "wasm-cfg-stackify"
42950a13cfSDan Gohman
43ed41945fSHeejin Ahn STATISTIC(NumCallUnwindMismatches, "Number of call unwind mismatches found");
449f770b36SHeejin Ahn STATISTIC(NumCatchUnwindMismatches, "Number of catch unwind mismatches found");
45c4ac74fbSHeejin Ahn
46950a13cfSDan Gohman namespace {
47950a13cfSDan Gohman class WebAssemblyCFGStackify final : public MachineFunctionPass {
getPassName() const48117296c0SMehdi Amini StringRef getPassName() const override { return "WebAssembly CFG Stackify"; }
49950a13cfSDan Gohman
getAnalysisUsage(AnalysisUsage & AU) const50950a13cfSDan Gohman void getAnalysisUsage(AnalysisUsage &AU) const override {
5132807932SDan Gohman AU.addRequired<MachineDominatorTree>();
52950a13cfSDan Gohman AU.addRequired<MachineLoopInfo>();
53e76fa9ecSHeejin Ahn AU.addRequired<WebAssemblyExceptionInfo>();
54950a13cfSDan Gohman MachineFunctionPass::getAnalysisUsage(AU);
55950a13cfSDan Gohman }
56950a13cfSDan Gohman
57950a13cfSDan Gohman bool runOnMachineFunction(MachineFunction &MF) override;
58950a13cfSDan Gohman
59e76fa9ecSHeejin Ahn // For each block whose label represents the end of a scope, record the block
60e76fa9ecSHeejin Ahn // which holds the beginning of the scope. This will allow us to quickly skip
61e76fa9ecSHeejin Ahn // over scoped regions when walking blocks.
62e76fa9ecSHeejin Ahn SmallVector<MachineBasicBlock *, 8> ScopeTops;
updateScopeTops(MachineBasicBlock * Begin,MachineBasicBlock * End)631cc52357SHeejin Ahn void updateScopeTops(MachineBasicBlock *Begin, MachineBasicBlock *End) {
641cc52357SHeejin Ahn int EndNo = End->getNumber();
651cc52357SHeejin Ahn if (!ScopeTops[EndNo] || ScopeTops[EndNo]->getNumber() > Begin->getNumber())
661cc52357SHeejin Ahn ScopeTops[EndNo] = Begin;
671cc52357SHeejin Ahn }
68e76fa9ecSHeejin Ahn
69c4ac74fbSHeejin Ahn // Placing markers.
70e76fa9ecSHeejin Ahn void placeMarkers(MachineFunction &MF);
71e76fa9ecSHeejin Ahn void placeBlockMarker(MachineBasicBlock &MBB);
72e76fa9ecSHeejin Ahn void placeLoopMarker(MachineBasicBlock &MBB);
73e76fa9ecSHeejin Ahn void placeTryMarker(MachineBasicBlock &MBB);
74ed41945fSHeejin Ahn
75ed41945fSHeejin Ahn // Exception handling related functions
76ed41945fSHeejin Ahn bool fixCallUnwindMismatches(MachineFunction &MF);
77ed41945fSHeejin Ahn bool fixCatchUnwindMismatches(MachineFunction &MF);
78ed41945fSHeejin Ahn void addTryDelegate(MachineInstr *RangeBegin, MachineInstr *RangeEnd,
79ed41945fSHeejin Ahn MachineBasicBlock *DelegateDest);
80ed41945fSHeejin Ahn void recalculateScopeTops(MachineFunction &MF);
81cf699b45SHeejin Ahn void removeUnnecessaryInstrs(MachineFunction &MF);
82ed41945fSHeejin Ahn
83ed41945fSHeejin Ahn // Wrap-up
842968611fSHeejin Ahn using EndMarkerInfo =
852968611fSHeejin Ahn std::pair<const MachineBasicBlock *, const MachineInstr *>;
862968611fSHeejin Ahn unsigned getBranchDepth(const SmallVectorImpl<EndMarkerInfo> &Stack,
872968611fSHeejin Ahn const MachineBasicBlock *MBB);
882968611fSHeejin Ahn unsigned getDelegateDepth(const SmallVectorImpl<EndMarkerInfo> &Stack,
89ed41945fSHeejin Ahn const MachineBasicBlock *MBB);
9035f5f797SHeejin Ahn unsigned
9135f5f797SHeejin Ahn getRethrowDepth(const SmallVectorImpl<EndMarkerInfo> &Stack,
9235f5f797SHeejin Ahn const SmallVectorImpl<const MachineBasicBlock *> &EHPadStack);
93e76fa9ecSHeejin Ahn void rewriteDepthImmediates(MachineFunction &MF);
94e76fa9ecSHeejin Ahn void fixEndsAtEndOfFunction(MachineFunction &MF);
95ed41945fSHeejin Ahn void cleanupFunctionData(MachineFunction &MF);
96e76fa9ecSHeejin Ahn
97ed41945fSHeejin Ahn // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY) or DELEGATE
98ed41945fSHeejin Ahn // (in case of TRY).
99e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd;
100ed41945fSHeejin Ahn // For each END_(BLOCK|LOOP|TRY) or DELEGATE, the corresponding
101ed41945fSHeejin Ahn // BLOCK|LOOP|TRY.
102e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineInstr *> EndToBegin;
103e76fa9ecSHeejin Ahn // <TRY marker, EH pad> map
104e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad;
105e76fa9ecSHeejin Ahn // <EH pad, TRY marker> map
106e76fa9ecSHeejin Ahn DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry;
107e76fa9ecSHeejin Ahn
108ed41945fSHeejin Ahn // We need an appendix block to place 'end_loop' or 'end_try' marker when the
109ed41945fSHeejin Ahn // loop / exception bottom block is the last block in a function
110c4ac74fbSHeejin Ahn MachineBasicBlock *AppendixBB = nullptr;
getAppendixBlock(MachineFunction & MF)111c4ac74fbSHeejin Ahn MachineBasicBlock *getAppendixBlock(MachineFunction &MF) {
112c4ac74fbSHeejin Ahn if (!AppendixBB) {
113c4ac74fbSHeejin Ahn AppendixBB = MF.CreateMachineBasicBlock();
114c4ac74fbSHeejin Ahn // Give it a fake predecessor so that AsmPrinter prints its label.
115c4ac74fbSHeejin Ahn AppendixBB->addSuccessor(AppendixBB);
116c4ac74fbSHeejin Ahn MF.push_back(AppendixBB);
117c4ac74fbSHeejin Ahn }
118c4ac74fbSHeejin Ahn return AppendixBB;
119c4ac74fbSHeejin Ahn }
120c4ac74fbSHeejin Ahn
121ed41945fSHeejin Ahn // Before running rewriteDepthImmediates function, 'delegate' has a BB as its
122ed41945fSHeejin Ahn // destination operand. getFakeCallerBlock() returns a fake BB that will be
123ed41945fSHeejin Ahn // used for the operand when 'delegate' needs to rethrow to the caller. This
124ed41945fSHeejin Ahn // will be rewritten as an immediate value that is the number of block depths
125ed41945fSHeejin Ahn // + 1 in rewriteDepthImmediates, and this fake BB will be removed at the end
126ed41945fSHeejin Ahn // of the pass.
127ed41945fSHeejin Ahn MachineBasicBlock *FakeCallerBB = nullptr;
getFakeCallerBlock(MachineFunction & MF)128ed41945fSHeejin Ahn MachineBasicBlock *getFakeCallerBlock(MachineFunction &MF) {
129ed41945fSHeejin Ahn if (!FakeCallerBB)
130ed41945fSHeejin Ahn FakeCallerBB = MF.CreateMachineBasicBlock();
131ed41945fSHeejin Ahn return FakeCallerBB;
132ed41945fSHeejin Ahn }
133ed41945fSHeejin Ahn
134cf699b45SHeejin Ahn // Helper functions to register / unregister scope information created by
135cf699b45SHeejin Ahn // marker instructions.
136e76fa9ecSHeejin Ahn void registerScope(MachineInstr *Begin, MachineInstr *End);
137e76fa9ecSHeejin Ahn void registerTryScope(MachineInstr *Begin, MachineInstr *End,
138e76fa9ecSHeejin Ahn MachineBasicBlock *EHPad);
139cf699b45SHeejin Ahn void unregisterScope(MachineInstr *Begin);
140e76fa9ecSHeejin Ahn
141950a13cfSDan Gohman public:
142950a13cfSDan Gohman static char ID; // Pass identification, replacement for typeid
WebAssemblyCFGStackify()143950a13cfSDan Gohman WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
~WebAssemblyCFGStackify()144e76fa9ecSHeejin Ahn ~WebAssemblyCFGStackify() override { releaseMemory(); }
145e76fa9ecSHeejin Ahn void releaseMemory() override;
146950a13cfSDan Gohman };
147950a13cfSDan Gohman } // end anonymous namespace
148950a13cfSDan Gohman
149950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0;
15040926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE,
151c4ac74fbSHeejin Ahn "Insert BLOCK/LOOP/TRY markers for WebAssembly scopes", false,
152f208f631SHeejin Ahn false)
15340926451SJacob Gravelle
createWebAssemblyCFGStackify()154950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() {
155950a13cfSDan Gohman return new WebAssemblyCFGStackify();
156950a13cfSDan Gohman }
157950a13cfSDan Gohman
158b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as
159b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized
160b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough
161b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any
162b3aa1ecaSDan Gohman /// explicit mentions.
explicitlyBranchesTo(MachineBasicBlock * Pred,MachineBasicBlock * MBB)16318c56a07SHeejin Ahn static bool explicitlyBranchesTo(MachineBasicBlock *Pred,
16435e4a289SDan Gohman MachineBasicBlock *MBB) {
165b3aa1ecaSDan Gohman for (MachineInstr &MI : Pred->terminators())
166b3aa1ecaSDan Gohman for (MachineOperand &MO : MI.explicit_operands())
167b3aa1ecaSDan Gohman if (MO.isMBB() && MO.getMBB() == MBB)
168b3aa1ecaSDan Gohman return true;
169b3aa1ecaSDan Gohman return false;
170b3aa1ecaSDan Gohman }
171b3aa1ecaSDan Gohman
172e76fa9ecSHeejin Ahn // Returns an iterator to the earliest position possible within the MBB,
173e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
174e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains
175e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, AfterSet is only
1765b8bbbecSZarko Todorovski // used for validation checking.
1771cc52357SHeejin Ahn template <typename Container>
178e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator
getEarliestInsertPos(MachineBasicBlock * MBB,const Container & BeforeSet,const Container & AfterSet)1791cc52357SHeejin Ahn getEarliestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet,
1801cc52357SHeejin Ahn const Container &AfterSet) {
181e76fa9ecSHeejin Ahn auto InsertPos = MBB->end();
182e76fa9ecSHeejin Ahn while (InsertPos != MBB->begin()) {
183e76fa9ecSHeejin Ahn if (BeforeSet.count(&*std::prev(InsertPos))) {
184e76fa9ecSHeejin Ahn #ifndef NDEBUG
1855b8bbbecSZarko Todorovski // Validation check
186e76fa9ecSHeejin Ahn for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos)
187e76fa9ecSHeejin Ahn assert(!AfterSet.count(&*std::prev(Pos)));
188e76fa9ecSHeejin Ahn #endif
189e76fa9ecSHeejin Ahn break;
190e76fa9ecSHeejin Ahn }
191e76fa9ecSHeejin Ahn --InsertPos;
192e76fa9ecSHeejin Ahn }
193e76fa9ecSHeejin Ahn return InsertPos;
194e76fa9ecSHeejin Ahn }
195e76fa9ecSHeejin Ahn
196e76fa9ecSHeejin Ahn // Returns an iterator to the latest position possible within the MBB,
197e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
198e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains
199e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, BeforeSet is only
2005b8bbbecSZarko Todorovski // used for validation checking.
2011cc52357SHeejin Ahn template <typename Container>
202e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator
getLatestInsertPos(MachineBasicBlock * MBB,const Container & BeforeSet,const Container & AfterSet)2031cc52357SHeejin Ahn getLatestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet,
2041cc52357SHeejin Ahn const Container &AfterSet) {
205e76fa9ecSHeejin Ahn auto InsertPos = MBB->begin();
206e76fa9ecSHeejin Ahn while (InsertPos != MBB->end()) {
207e76fa9ecSHeejin Ahn if (AfterSet.count(&*InsertPos)) {
208e76fa9ecSHeejin Ahn #ifndef NDEBUG
2095b8bbbecSZarko Todorovski // Validation check
210e76fa9ecSHeejin Ahn for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos)
211e76fa9ecSHeejin Ahn assert(!BeforeSet.count(&*Pos));
212e76fa9ecSHeejin Ahn #endif
213e76fa9ecSHeejin Ahn break;
214e76fa9ecSHeejin Ahn }
215e76fa9ecSHeejin Ahn ++InsertPos;
216e76fa9ecSHeejin Ahn }
217e76fa9ecSHeejin Ahn return InsertPos;
218e76fa9ecSHeejin Ahn }
219e76fa9ecSHeejin Ahn
registerScope(MachineInstr * Begin,MachineInstr * End)220e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin,
221e76fa9ecSHeejin Ahn MachineInstr *End) {
222e76fa9ecSHeejin Ahn BeginToEnd[Begin] = End;
223e76fa9ecSHeejin Ahn EndToBegin[End] = Begin;
224e76fa9ecSHeejin Ahn }
225e76fa9ecSHeejin Ahn
226ed41945fSHeejin Ahn // When 'End' is not an 'end_try' but 'delegate, EHPad is nullptr.
registerTryScope(MachineInstr * Begin,MachineInstr * End,MachineBasicBlock * EHPad)227e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin,
228e76fa9ecSHeejin Ahn MachineInstr *End,
229e76fa9ecSHeejin Ahn MachineBasicBlock *EHPad) {
230e76fa9ecSHeejin Ahn registerScope(Begin, End);
231e76fa9ecSHeejin Ahn TryToEHPad[Begin] = EHPad;
232e76fa9ecSHeejin Ahn EHPadToTry[EHPad] = Begin;
233e76fa9ecSHeejin Ahn }
234e76fa9ecSHeejin Ahn
unregisterScope(MachineInstr * Begin)235cf699b45SHeejin Ahn void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) {
236cf699b45SHeejin Ahn assert(BeginToEnd.count(Begin));
237cf699b45SHeejin Ahn MachineInstr *End = BeginToEnd[Begin];
238cf699b45SHeejin Ahn assert(EndToBegin.count(End));
239cf699b45SHeejin Ahn BeginToEnd.erase(Begin);
240cf699b45SHeejin Ahn EndToBegin.erase(End);
241cf699b45SHeejin Ahn MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin);
242cf699b45SHeejin Ahn if (EHPad) {
243cf699b45SHeejin Ahn assert(EHPadToTry.count(EHPad));
244cf699b45SHeejin Ahn TryToEHPad.erase(Begin);
245cf699b45SHeejin Ahn EHPadToTry.erase(EHPad);
246cf699b45SHeejin Ahn }
247cf699b45SHeejin Ahn }
248cf699b45SHeejin Ahn
24932807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed).
250c4ac74fbSHeejin Ahn // TODO Consider a more generalized way of handling block (and also loop and
251c4ac74fbSHeejin Ahn // try) signatures when we implement the multi-value proposal later.
placeBlockMarker(MachineBasicBlock & MBB)252e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) {
25344a5a4b1SHeejin Ahn assert(!MBB.isEHPad());
254e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent();
255e76fa9ecSHeejin Ahn auto &MDT = getAnalysis<MachineDominatorTree>();
256e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
257e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
258e76fa9ecSHeejin Ahn
2598fe7e86bSDan Gohman // First compute the nearest common dominator of all forward non-fallthrough
2608fe7e86bSDan Gohman // predecessors so that we minimize the time that the BLOCK is on the stack,
2618fe7e86bSDan Gohman // which reduces overall stack height.
26232807932SDan Gohman MachineBasicBlock *Header = nullptr;
26332807932SDan Gohman bool IsBranchedTo = false;
26432807932SDan Gohman int MBBNumber = MBB.getNumber();
265e76fa9ecSHeejin Ahn for (MachineBasicBlock *Pred : MBB.predecessors()) {
26632807932SDan Gohman if (Pred->getNumber() < MBBNumber) {
26732807932SDan Gohman Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
26852e240a0SHeejin Ahn if (explicitlyBranchesTo(Pred, &MBB))
26932807932SDan Gohman IsBranchedTo = true;
27032807932SDan Gohman }
271e76fa9ecSHeejin Ahn }
27232807932SDan Gohman if (!Header)
27332807932SDan Gohman return;
27432807932SDan Gohman if (!IsBranchedTo)
27532807932SDan Gohman return;
27632807932SDan Gohman
2778fe7e86bSDan Gohman assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
2785c644c9bSHeejin Ahn MachineBasicBlock *LayoutPred = MBB.getPrevNode();
2798fe7e86bSDan Gohman
2808fe7e86bSDan Gohman // If the nearest common dominator is inside a more deeply nested context,
2818fe7e86bSDan Gohman // walk out to the nearest scope which isn't more deeply nested.
2828fe7e86bSDan Gohman for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
2838fe7e86bSDan Gohman if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
2848fe7e86bSDan Gohman if (ScopeTop->getNumber() > Header->getNumber()) {
2858fe7e86bSDan Gohman // Skip over an intervening scope.
2865c644c9bSHeejin Ahn I = std::next(ScopeTop->getIterator());
2878fe7e86bSDan Gohman } else {
2888fe7e86bSDan Gohman // We found a scope level at an appropriate depth.
2898fe7e86bSDan Gohman Header = ScopeTop;
2908fe7e86bSDan Gohman break;
2918fe7e86bSDan Gohman }
2928fe7e86bSDan Gohman }
2938fe7e86bSDan Gohman }
2948fe7e86bSDan Gohman
2958fe7e86bSDan Gohman // Decide where in Header to put the BLOCK.
296e76fa9ecSHeejin Ahn
297e76fa9ecSHeejin Ahn // Instructions that should go before the BLOCK.
298e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet;
299e76fa9ecSHeejin Ahn // Instructions that should go after the BLOCK.
300e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet;
301e76fa9ecSHeejin Ahn for (const auto &MI : *Header) {
30244a5a4b1SHeejin Ahn // If there is a previously placed LOOP marker and the bottom block of the
30344a5a4b1SHeejin Ahn // loop is above MBB, it should be after the BLOCK, because the loop is
30444a5a4b1SHeejin Ahn // nested in this BLOCK. Otherwise it should be before the BLOCK.
30544a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP) {
30644a5a4b1SHeejin Ahn auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
30744a5a4b1SHeejin Ahn if (MBB.getNumber() > LoopBottom->getNumber())
308e76fa9ecSHeejin Ahn AfterSet.insert(&MI);
309e76fa9ecSHeejin Ahn #ifndef NDEBUG
310e76fa9ecSHeejin Ahn else
311e76fa9ecSHeejin Ahn BeforeSet.insert(&MI);
312e76fa9ecSHeejin Ahn #endif
313e76fa9ecSHeejin Ahn }
314e76fa9ecSHeejin Ahn
315834debffSHeejin Ahn // If there is a previously placed BLOCK/TRY marker and its corresponding
316834debffSHeejin Ahn // END marker is before the current BLOCK's END marker, that should be
317834debffSHeejin Ahn // placed after this BLOCK. Otherwise it should be placed before this BLOCK
318834debffSHeejin Ahn // marker.
31944a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::BLOCK ||
320834debffSHeejin Ahn MI.getOpcode() == WebAssembly::TRY) {
321834debffSHeejin Ahn if (BeginToEnd[&MI]->getParent()->getNumber() <= MBB.getNumber())
322e76fa9ecSHeejin Ahn AfterSet.insert(&MI);
323834debffSHeejin Ahn #ifndef NDEBUG
324834debffSHeejin Ahn else
325834debffSHeejin Ahn BeforeSet.insert(&MI);
326834debffSHeejin Ahn #endif
327834debffSHeejin Ahn }
328e76fa9ecSHeejin Ahn
329e76fa9ecSHeejin Ahn #ifndef NDEBUG
330e76fa9ecSHeejin Ahn // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK.
331e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_BLOCK ||
332e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_LOOP ||
333e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY)
334e76fa9ecSHeejin Ahn BeforeSet.insert(&MI);
335e76fa9ecSHeejin Ahn #endif
336e76fa9ecSHeejin Ahn
337e76fa9ecSHeejin Ahn // Terminators should go after the BLOCK.
338e76fa9ecSHeejin Ahn if (MI.isTerminator())
339e76fa9ecSHeejin Ahn AfterSet.insert(&MI);
340e76fa9ecSHeejin Ahn }
341e76fa9ecSHeejin Ahn
342e76fa9ecSHeejin Ahn // Local expression tree should go after the BLOCK.
343e76fa9ecSHeejin Ahn for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
344e76fa9ecSHeejin Ahn --I) {
345409b4391SYury Delendik if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
346409b4391SYury Delendik continue;
347e76fa9ecSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI))
348e76fa9ecSHeejin Ahn AfterSet.insert(&*std::prev(I));
349e76fa9ecSHeejin Ahn else
350e76fa9ecSHeejin Ahn break;
35132807932SDan Gohman }
35232807932SDan Gohman
3538fe7e86bSDan Gohman // Add the BLOCK.
3542cb27072SThomas Lively WebAssembly::BlockType ReturnType = WebAssembly::BlockType::Void;
35518c56a07SHeejin Ahn auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
35692401cc1SHeejin Ahn MachineInstr *Begin =
35792401cc1SHeejin Ahn BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
3582726b88cSDan Gohman TII.get(WebAssembly::BLOCK))
359d6f48786SHeejin Ahn .addImm(int64_t(ReturnType));
3601d68e80fSDan Gohman
361e76fa9ecSHeejin Ahn // Decide where in Header to put the END_BLOCK.
362e76fa9ecSHeejin Ahn BeforeSet.clear();
363e76fa9ecSHeejin Ahn AfterSet.clear();
364e76fa9ecSHeejin Ahn for (auto &MI : MBB) {
365e76fa9ecSHeejin Ahn #ifndef NDEBUG
366e76fa9ecSHeejin Ahn // END_BLOCK should precede existing LOOP and TRY markers.
367e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP ||
368e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::TRY)
369e76fa9ecSHeejin Ahn AfterSet.insert(&MI);
370e76fa9ecSHeejin Ahn #endif
371e76fa9ecSHeejin Ahn
372e76fa9ecSHeejin Ahn // If there is a previously placed END_LOOP marker and the header of the
373e76fa9ecSHeejin Ahn // loop is above this block's header, the END_LOOP should be placed after
374e76fa9ecSHeejin Ahn // the BLOCK, because the loop contains this block. Otherwise the END_LOOP
375e76fa9ecSHeejin Ahn // should be placed before the BLOCK. The same for END_TRY.
376e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP ||
377e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) {
378e76fa9ecSHeejin Ahn if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
379e76fa9ecSHeejin Ahn BeforeSet.insert(&MI);
380e76fa9ecSHeejin Ahn #ifndef NDEBUG
381e76fa9ecSHeejin Ahn else
382e76fa9ecSHeejin Ahn AfterSet.insert(&MI);
383e76fa9ecSHeejin Ahn #endif
384e76fa9ecSHeejin Ahn }
385e76fa9ecSHeejin Ahn }
386e76fa9ecSHeejin Ahn
3871d68e80fSDan Gohman // Mark the end of the block.
38818c56a07SHeejin Ahn InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
38910b31358SDerek Schuff MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
3902726b88cSDan Gohman TII.get(WebAssembly::END_BLOCK));
391e76fa9ecSHeejin Ahn registerScope(Begin, End);
3928fe7e86bSDan Gohman
3938fe7e86bSDan Gohman // Track the farthest-spanning scope that ends at this point.
3941cc52357SHeejin Ahn updateScopeTops(Header, &MBB);
395950a13cfSDan Gohman }
396950a13cfSDan Gohman
3978fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
placeLoopMarker(MachineBasicBlock & MBB)398e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) {
399e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent();
400e76fa9ecSHeejin Ahn const auto &MLI = getAnalysis<MachineLoopInfo>();
401276f9e8cSHeejin Ahn const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
402276f9e8cSHeejin Ahn SortRegionInfo SRI(MLI, WEI);
403e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
404e76fa9ecSHeejin Ahn
4058fe7e86bSDan Gohman MachineLoop *Loop = MLI.getLoopFor(&MBB);
4068fe7e86bSDan Gohman if (!Loop || Loop->getHeader() != &MBB)
4078fe7e86bSDan Gohman return;
4088fe7e86bSDan Gohman
4098fe7e86bSDan Gohman // The operand of a LOOP is the first block after the loop. If the loop is the
4108fe7e86bSDan Gohman // bottom of the function, insert a dummy block at the end.
411276f9e8cSHeejin Ahn MachineBasicBlock *Bottom = SRI.getBottom(Loop);
4125c644c9bSHeejin Ahn auto Iter = std::next(Bottom->getIterator());
413e3e4a5ffSDan Gohman if (Iter == MF.end()) {
414c4ac74fbSHeejin Ahn getAppendixBlock(MF);
4155c644c9bSHeejin Ahn Iter = std::next(Bottom->getIterator());
416e3e4a5ffSDan Gohman }
4178fe7e86bSDan Gohman MachineBasicBlock *AfterLoop = &*Iter;
418f6857223SDan Gohman
419e76fa9ecSHeejin Ahn // Decide where in Header to put the LOOP.
420e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet;
421e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet;
422e76fa9ecSHeejin Ahn for (const auto &MI : MBB) {
423e76fa9ecSHeejin Ahn // LOOP marker should be after any existing loop that ends here. Otherwise
424e76fa9ecSHeejin Ahn // we assume the instruction belongs to the loop.
425e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP)
426e76fa9ecSHeejin Ahn BeforeSet.insert(&MI);
427e76fa9ecSHeejin Ahn #ifndef NDEBUG
428e76fa9ecSHeejin Ahn else
429e76fa9ecSHeejin Ahn AfterSet.insert(&MI);
430e76fa9ecSHeejin Ahn #endif
431e76fa9ecSHeejin Ahn }
432e76fa9ecSHeejin Ahn
433e76fa9ecSHeejin Ahn // Mark the beginning of the loop.
43418c56a07SHeejin Ahn auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
43510b31358SDerek Schuff MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos),
4362726b88cSDan Gohman TII.get(WebAssembly::LOOP))
4372cb27072SThomas Lively .addImm(int64_t(WebAssembly::BlockType::Void));
4381d68e80fSDan Gohman
439e76fa9ecSHeejin Ahn // Decide where in Header to put the END_LOOP.
440e76fa9ecSHeejin Ahn BeforeSet.clear();
441e76fa9ecSHeejin Ahn AfterSet.clear();
442e76fa9ecSHeejin Ahn #ifndef NDEBUG
443e76fa9ecSHeejin Ahn for (const auto &MI : MBB)
444e76fa9ecSHeejin Ahn // Existing END_LOOP markers belong to parent loops of this loop
445e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP)
446e76fa9ecSHeejin Ahn AfterSet.insert(&MI);
447e76fa9ecSHeejin Ahn #endif
448e76fa9ecSHeejin Ahn
449e76fa9ecSHeejin Ahn // Mark the end of the loop (using arbitrary debug location that branched to
450e76fa9ecSHeejin Ahn // the loop end as its location).
45118c56a07SHeejin Ahn InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet);
45267f74aceSHeejin Ahn DebugLoc EndDL = AfterLoop->pred_empty()
45367f74aceSHeejin Ahn ? DebugLoc()
45467f74aceSHeejin Ahn : (*AfterLoop->pred_rbegin())->findBranchDebugLoc();
455e76fa9ecSHeejin Ahn MachineInstr *End =
456e76fa9ecSHeejin Ahn BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP));
457e76fa9ecSHeejin Ahn registerScope(Begin, End);
4588fe7e86bSDan Gohman
4598fe7e86bSDan Gohman assert((!ScopeTops[AfterLoop->getNumber()] ||
4608fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
461442bfcecSDan Gohman "With block sorting the outermost loop for a block should be first.");
4621cc52357SHeejin Ahn updateScopeTops(&MBB, AfterLoop);
463e3e4a5ffSDan Gohman }
464950a13cfSDan Gohman
placeTryMarker(MachineBasicBlock & MBB)465e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) {
46644a5a4b1SHeejin Ahn assert(MBB.isEHPad());
467e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent();
468e76fa9ecSHeejin Ahn auto &MDT = getAnalysis<MachineDominatorTree>();
469e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
470276f9e8cSHeejin Ahn const auto &MLI = getAnalysis<MachineLoopInfo>();
471e76fa9ecSHeejin Ahn const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
472276f9e8cSHeejin Ahn SortRegionInfo SRI(MLI, WEI);
473e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
474e76fa9ecSHeejin Ahn
475e76fa9ecSHeejin Ahn // Compute the nearest common dominator of all unwind predecessors
476e76fa9ecSHeejin Ahn MachineBasicBlock *Header = nullptr;
477e76fa9ecSHeejin Ahn int MBBNumber = MBB.getNumber();
478e76fa9ecSHeejin Ahn for (auto *Pred : MBB.predecessors()) {
479e76fa9ecSHeejin Ahn if (Pred->getNumber() < MBBNumber) {
480e76fa9ecSHeejin Ahn Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
48118c56a07SHeejin Ahn assert(!explicitlyBranchesTo(Pred, &MBB) &&
482e76fa9ecSHeejin Ahn "Explicit branch to an EH pad!");
483e76fa9ecSHeejin Ahn }
484e76fa9ecSHeejin Ahn }
485e76fa9ecSHeejin Ahn if (!Header)
486e76fa9ecSHeejin Ahn return;
487e76fa9ecSHeejin Ahn
488e76fa9ecSHeejin Ahn // If this try is at the bottom of the function, insert a dummy block at the
489e76fa9ecSHeejin Ahn // end.
490e76fa9ecSHeejin Ahn WebAssemblyException *WE = WEI.getExceptionFor(&MBB);
491e76fa9ecSHeejin Ahn assert(WE);
492276f9e8cSHeejin Ahn MachineBasicBlock *Bottom = SRI.getBottom(WE);
493e76fa9ecSHeejin Ahn
4945c644c9bSHeejin Ahn auto Iter = std::next(Bottom->getIterator());
495e76fa9ecSHeejin Ahn if (Iter == MF.end()) {
496c4ac74fbSHeejin Ahn getAppendixBlock(MF);
4975c644c9bSHeejin Ahn Iter = std::next(Bottom->getIterator());
498e76fa9ecSHeejin Ahn }
49920cf0749SHeejin Ahn MachineBasicBlock *Cont = &*Iter;
500e76fa9ecSHeejin Ahn
50120cf0749SHeejin Ahn assert(Cont != &MF.front());
5025c644c9bSHeejin Ahn MachineBasicBlock *LayoutPred = Cont->getPrevNode();
503e76fa9ecSHeejin Ahn
504e76fa9ecSHeejin Ahn // If the nearest common dominator is inside a more deeply nested context,
505e76fa9ecSHeejin Ahn // walk out to the nearest scope which isn't more deeply nested.
506e76fa9ecSHeejin Ahn for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
507e76fa9ecSHeejin Ahn if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
508e76fa9ecSHeejin Ahn if (ScopeTop->getNumber() > Header->getNumber()) {
509e76fa9ecSHeejin Ahn // Skip over an intervening scope.
5105c644c9bSHeejin Ahn I = std::next(ScopeTop->getIterator());
511e76fa9ecSHeejin Ahn } else {
512e76fa9ecSHeejin Ahn // We found a scope level at an appropriate depth.
513e76fa9ecSHeejin Ahn Header = ScopeTop;
514e76fa9ecSHeejin Ahn break;
515e76fa9ecSHeejin Ahn }
516e76fa9ecSHeejin Ahn }
517e76fa9ecSHeejin Ahn }
518e76fa9ecSHeejin Ahn
519e76fa9ecSHeejin Ahn // Decide where in Header to put the TRY.
520e76fa9ecSHeejin Ahn
52144a5a4b1SHeejin Ahn // Instructions that should go before the TRY.
522e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet;
52344a5a4b1SHeejin Ahn // Instructions that should go after the TRY.
524e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet;
525e76fa9ecSHeejin Ahn for (const auto &MI : *Header) {
52644a5a4b1SHeejin Ahn // If there is a previously placed LOOP marker and the bottom block of the
52744a5a4b1SHeejin Ahn // loop is above MBB, it should be after the TRY, because the loop is nested
52844a5a4b1SHeejin Ahn // in this TRY. Otherwise it should be before the TRY.
529e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP) {
53044a5a4b1SHeejin Ahn auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
53144a5a4b1SHeejin Ahn if (MBB.getNumber() > LoopBottom->getNumber())
532e76fa9ecSHeejin Ahn AfterSet.insert(&MI);
533e76fa9ecSHeejin Ahn #ifndef NDEBUG
534e76fa9ecSHeejin Ahn else
535e76fa9ecSHeejin Ahn BeforeSet.insert(&MI);
536e76fa9ecSHeejin Ahn #endif
537e76fa9ecSHeejin Ahn }
538e76fa9ecSHeejin Ahn
53944a5a4b1SHeejin Ahn // All previously inserted BLOCK/TRY markers should be after the TRY because
54044a5a4b1SHeejin Ahn // they are all nested trys.
54144a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::BLOCK ||
54244a5a4b1SHeejin Ahn MI.getOpcode() == WebAssembly::TRY)
543e76fa9ecSHeejin Ahn AfterSet.insert(&MI);
544e76fa9ecSHeejin Ahn
545e76fa9ecSHeejin Ahn #ifndef NDEBUG
54644a5a4b1SHeejin Ahn // All END_(BLOCK/LOOP/TRY) markers should be before the TRY.
54744a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::END_BLOCK ||
54844a5a4b1SHeejin Ahn MI.getOpcode() == WebAssembly::END_LOOP ||
549e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY)
550e76fa9ecSHeejin Ahn BeforeSet.insert(&MI);
551e76fa9ecSHeejin Ahn #endif
552e76fa9ecSHeejin Ahn
553e76fa9ecSHeejin Ahn // Terminators should go after the TRY.
554e76fa9ecSHeejin Ahn if (MI.isTerminator())
555e76fa9ecSHeejin Ahn AfterSet.insert(&MI);
556e76fa9ecSHeejin Ahn }
557e76fa9ecSHeejin Ahn
5586a37c5d6SHeejin Ahn // If Header unwinds to MBB (= Header contains 'invoke'), the try block should
5596a37c5d6SHeejin Ahn // contain the call within it. So the call should go after the TRY. The
5606a37c5d6SHeejin Ahn // exception is when the header's terminator is a rethrow instruction, in
5616a37c5d6SHeejin Ahn // which case that instruction, not a call instruction before it, is gonna
5626a37c5d6SHeejin Ahn // throw.
5636a37c5d6SHeejin Ahn MachineInstr *ThrowingCall = nullptr;
5646a37c5d6SHeejin Ahn if (MBB.isPredecessor(Header)) {
5656a37c5d6SHeejin Ahn auto TermPos = Header->getFirstTerminator();
5666a37c5d6SHeejin Ahn if (TermPos == Header->end() ||
5676a37c5d6SHeejin Ahn TermPos->getOpcode() != WebAssembly::RETHROW) {
5686a37c5d6SHeejin Ahn for (auto &MI : reverse(*Header)) {
5696a37c5d6SHeejin Ahn if (MI.isCall()) {
5706a37c5d6SHeejin Ahn AfterSet.insert(&MI);
5716a37c5d6SHeejin Ahn ThrowingCall = &MI;
5726a37c5d6SHeejin Ahn // Possibly throwing calls are usually wrapped by EH_LABEL
5736a37c5d6SHeejin Ahn // instructions. We don't want to split them and the call.
5746a37c5d6SHeejin Ahn if (MI.getIterator() != Header->begin() &&
5756a37c5d6SHeejin Ahn std::prev(MI.getIterator())->isEHLabel()) {
5766a37c5d6SHeejin Ahn AfterSet.insert(&*std::prev(MI.getIterator()));
5776a37c5d6SHeejin Ahn ThrowingCall = &*std::prev(MI.getIterator());
5786a37c5d6SHeejin Ahn }
5796a37c5d6SHeejin Ahn break;
5806a37c5d6SHeejin Ahn }
5816a37c5d6SHeejin Ahn }
5826a37c5d6SHeejin Ahn }
5836a37c5d6SHeejin Ahn }
5846a37c5d6SHeejin Ahn
585e76fa9ecSHeejin Ahn // Local expression tree should go after the TRY.
5866a37c5d6SHeejin Ahn // For BLOCK placement, we start the search from the previous instruction of a
5876a37c5d6SHeejin Ahn // BB's terminator, but in TRY's case, we should start from the previous
5886a37c5d6SHeejin Ahn // instruction of a call that can throw, or a EH_LABEL that precedes the call,
5896a37c5d6SHeejin Ahn // because the return values of the call's previous instructions can be
5906a37c5d6SHeejin Ahn // stackified and consumed by the throwing call.
5916a37c5d6SHeejin Ahn auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall)
5926a37c5d6SHeejin Ahn : Header->getFirstTerminator();
5936a37c5d6SHeejin Ahn for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) {
594409b4391SYury Delendik if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
595409b4391SYury Delendik continue;
596e76fa9ecSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI))
597e76fa9ecSHeejin Ahn AfterSet.insert(&*std::prev(I));
598e76fa9ecSHeejin Ahn else
599e76fa9ecSHeejin Ahn break;
600e76fa9ecSHeejin Ahn }
601e76fa9ecSHeejin Ahn
602e76fa9ecSHeejin Ahn // Add the TRY.
60318c56a07SHeejin Ahn auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
604e76fa9ecSHeejin Ahn MachineInstr *Begin =
605e76fa9ecSHeejin Ahn BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
606e76fa9ecSHeejin Ahn TII.get(WebAssembly::TRY))
6072cb27072SThomas Lively .addImm(int64_t(WebAssembly::BlockType::Void));
608e76fa9ecSHeejin Ahn
609e76fa9ecSHeejin Ahn // Decide where in Header to put the END_TRY.
610e76fa9ecSHeejin Ahn BeforeSet.clear();
611e76fa9ecSHeejin Ahn AfterSet.clear();
61220cf0749SHeejin Ahn for (const auto &MI : *Cont) {
613e76fa9ecSHeejin Ahn #ifndef NDEBUG
61444a5a4b1SHeejin Ahn // END_TRY should precede existing LOOP and BLOCK markers.
61544a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP ||
61644a5a4b1SHeejin Ahn MI.getOpcode() == WebAssembly::BLOCK)
617e76fa9ecSHeejin Ahn AfterSet.insert(&MI);
618e76fa9ecSHeejin Ahn
619e76fa9ecSHeejin Ahn // All END_TRY markers placed earlier belong to exceptions that contains
620e76fa9ecSHeejin Ahn // this one.
621e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_TRY)
622e76fa9ecSHeejin Ahn AfterSet.insert(&MI);
623e76fa9ecSHeejin Ahn #endif
624e76fa9ecSHeejin Ahn
625e76fa9ecSHeejin Ahn // If there is a previously placed END_LOOP marker and its header is after
626e76fa9ecSHeejin Ahn // where TRY marker is, this loop is contained within the 'catch' part, so
627e76fa9ecSHeejin Ahn // the END_TRY marker should go after that. Otherwise, the whole try-catch
628e76fa9ecSHeejin Ahn // is contained within this loop, so the END_TRY should go before that.
629e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) {
630222718fdSHeejin Ahn // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they
631222718fdSHeejin Ahn // are in the same BB, LOOP is always before TRY.
632222718fdSHeejin Ahn if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber())
633e76fa9ecSHeejin Ahn BeforeSet.insert(&MI);
634e76fa9ecSHeejin Ahn #ifndef NDEBUG
635e76fa9ecSHeejin Ahn else
636e76fa9ecSHeejin Ahn AfterSet.insert(&MI);
637e76fa9ecSHeejin Ahn #endif
638e76fa9ecSHeejin Ahn }
63944a5a4b1SHeejin Ahn
64044a5a4b1SHeejin Ahn // It is not possible for an END_BLOCK to be already in this block.
641e76fa9ecSHeejin Ahn }
642e76fa9ecSHeejin Ahn
643e76fa9ecSHeejin Ahn // Mark the end of the TRY.
64420cf0749SHeejin Ahn InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet);
645e76fa9ecSHeejin Ahn MachineInstr *End =
64620cf0749SHeejin Ahn BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(),
647e76fa9ecSHeejin Ahn TII.get(WebAssembly::END_TRY));
648e76fa9ecSHeejin Ahn registerTryScope(Begin, End, &MBB);
649e76fa9ecSHeejin Ahn
65082da1ffcSHeejin Ahn // Track the farthest-spanning scope that ends at this point. We create two
65182da1ffcSHeejin Ahn // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB
65282da1ffcSHeejin Ahn // with 'try'). We need to create 'catch' -> 'try' mapping here too because
65382da1ffcSHeejin Ahn // markers should not span across 'catch'. For example, this should not
65482da1ffcSHeejin Ahn // happen:
65582da1ffcSHeejin Ahn //
65682da1ffcSHeejin Ahn // try
65782da1ffcSHeejin Ahn // block --| (X)
65882da1ffcSHeejin Ahn // catch |
65982da1ffcSHeejin Ahn // end_block --|
66082da1ffcSHeejin Ahn // end_try
6611cc52357SHeejin Ahn for (auto *End : {&MBB, Cont})
6621cc52357SHeejin Ahn updateScopeTops(Header, End);
66382da1ffcSHeejin Ahn }
664e76fa9ecSHeejin Ahn
removeUnnecessaryInstrs(MachineFunction & MF)665cf699b45SHeejin Ahn void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) {
666cf699b45SHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
667cf699b45SHeejin Ahn
668cf699b45SHeejin Ahn // When there is an unconditional branch right before a catch instruction and
669cf699b45SHeejin Ahn // it branches to the end of end_try marker, we don't need the branch, because
670cf699b45SHeejin Ahn // it there is no exception, the control flow transfers to that point anyway.
671cf699b45SHeejin Ahn // bb0:
672cf699b45SHeejin Ahn // try
673cf699b45SHeejin Ahn // ...
674cf699b45SHeejin Ahn // br bb2 <- Not necessary
675c93b9559SHeejin Ahn // bb1 (ehpad):
676cf699b45SHeejin Ahn // catch
677cf699b45SHeejin Ahn // ...
678c93b9559SHeejin Ahn // bb2: <- Continuation BB
679cf699b45SHeejin Ahn // end
680c93b9559SHeejin Ahn //
681c93b9559SHeejin Ahn // A more involved case: When the BB where 'end' is located is an another EH
682c93b9559SHeejin Ahn // pad, the Cont (= continuation) BB is that EH pad's 'end' BB. For example,
683c93b9559SHeejin Ahn // bb0:
684c93b9559SHeejin Ahn // try
685c93b9559SHeejin Ahn // try
686c93b9559SHeejin Ahn // ...
687c93b9559SHeejin Ahn // br bb3 <- Not necessary
688c93b9559SHeejin Ahn // bb1 (ehpad):
689c93b9559SHeejin Ahn // catch
690c93b9559SHeejin Ahn // bb2 (ehpad):
691c93b9559SHeejin Ahn // end
692c93b9559SHeejin Ahn // catch
693c93b9559SHeejin Ahn // ...
694c93b9559SHeejin Ahn // bb3: <- Continuation BB
695c93b9559SHeejin Ahn // end
696c93b9559SHeejin Ahn //
697c93b9559SHeejin Ahn // When the EH pad at hand is bb1, its matching end_try is in bb2. But it is
698c93b9559SHeejin Ahn // another EH pad, so bb0's continuation BB becomes bb3. So 'br bb3' in the
699c93b9559SHeejin Ahn // code can be deleted. This is why we run 'while' until 'Cont' is not an EH
700c93b9559SHeejin Ahn // pad.
701cf699b45SHeejin Ahn for (auto &MBB : MF) {
702cf699b45SHeejin Ahn if (!MBB.isEHPad())
703cf699b45SHeejin Ahn continue;
704cf699b45SHeejin Ahn
705cf699b45SHeejin Ahn MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
706cf699b45SHeejin Ahn SmallVector<MachineOperand, 4> Cond;
7075c644c9bSHeejin Ahn MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode();
708c93b9559SHeejin Ahn
709c93b9559SHeejin Ahn MachineBasicBlock *Cont = &MBB;
710c93b9559SHeejin Ahn while (Cont->isEHPad()) {
711c93b9559SHeejin Ahn MachineInstr *Try = EHPadToTry[Cont];
712c93b9559SHeejin Ahn MachineInstr *EndTry = BeginToEnd[Try];
713ed41945fSHeejin Ahn // We started from an EH pad, so the end marker cannot be a delegate
714ed41945fSHeejin Ahn assert(EndTry->getOpcode() != WebAssembly::DELEGATE);
715c93b9559SHeejin Ahn Cont = EndTry->getParent();
716c93b9559SHeejin Ahn }
717c93b9559SHeejin Ahn
718cf699b45SHeejin Ahn bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond);
7193fe6ea46SHeejin Ahn // This condition means either
7203fe6ea46SHeejin Ahn // 1. This BB ends with a single unconditional branch whose destinaion is
7213fe6ea46SHeejin Ahn // Cont.
7223fe6ea46SHeejin Ahn // 2. This BB ends with a conditional branch followed by an unconditional
7233fe6ea46SHeejin Ahn // branch, and the unconditional branch's destination is Cont.
7243fe6ea46SHeejin Ahn // In both cases, we want to remove the last (= unconditional) branch.
725cf699b45SHeejin Ahn if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) ||
7263fe6ea46SHeejin Ahn (!Cond.empty() && FBB && FBB == Cont))) {
7273fe6ea46SHeejin Ahn bool ErasedUncondBr = false;
728a5099ad9SHeejin Ahn (void)ErasedUncondBr;
7293fe6ea46SHeejin Ahn for (auto I = EHPadLayoutPred->end(), E = EHPadLayoutPred->begin();
7303fe6ea46SHeejin Ahn I != E; --I) {
7313fe6ea46SHeejin Ahn auto PrevI = std::prev(I);
7323fe6ea46SHeejin Ahn if (PrevI->isTerminator()) {
7333fe6ea46SHeejin Ahn assert(PrevI->getOpcode() == WebAssembly::BR);
7343fe6ea46SHeejin Ahn PrevI->eraseFromParent();
7353fe6ea46SHeejin Ahn ErasedUncondBr = true;
7363fe6ea46SHeejin Ahn break;
7373fe6ea46SHeejin Ahn }
7383fe6ea46SHeejin Ahn }
7393fe6ea46SHeejin Ahn assert(ErasedUncondBr && "Unconditional branch not erased!");
7403fe6ea46SHeejin Ahn }
741cf699b45SHeejin Ahn }
742cf699b45SHeejin Ahn
743cf699b45SHeejin Ahn // When there are block / end_block markers that overlap with try / end_try
744cf699b45SHeejin Ahn // markers, and the block and try markers' return types are the same, the
745cf699b45SHeejin Ahn // block /end_block markers are not necessary, because try / end_try markers
746cf699b45SHeejin Ahn // also can serve as boundaries for branches.
747cf699b45SHeejin Ahn // block <- Not necessary
748cf699b45SHeejin Ahn // try
749cf699b45SHeejin Ahn // ...
750cf699b45SHeejin Ahn // catch
751cf699b45SHeejin Ahn // ...
752cf699b45SHeejin Ahn // end
753cf699b45SHeejin Ahn // end <- Not necessary
754cf699b45SHeejin Ahn SmallVector<MachineInstr *, 32> ToDelete;
755cf699b45SHeejin Ahn for (auto &MBB : MF) {
756cf699b45SHeejin Ahn for (auto &MI : MBB) {
757cf699b45SHeejin Ahn if (MI.getOpcode() != WebAssembly::TRY)
758cf699b45SHeejin Ahn continue;
759cf699b45SHeejin Ahn MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try];
760ed41945fSHeejin Ahn if (EndTry->getOpcode() == WebAssembly::DELEGATE)
761ed41945fSHeejin Ahn continue;
762ed41945fSHeejin Ahn
763cf699b45SHeejin Ahn MachineBasicBlock *TryBB = Try->getParent();
764cf699b45SHeejin Ahn MachineBasicBlock *Cont = EndTry->getParent();
765cf699b45SHeejin Ahn int64_t RetType = Try->getOperand(0).getImm();
7665c644c9bSHeejin Ahn for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator());
767cf699b45SHeejin Ahn B != TryBB->begin() && E != Cont->end() &&
768cf699b45SHeejin Ahn std::prev(B)->getOpcode() == WebAssembly::BLOCK &&
769cf699b45SHeejin Ahn E->getOpcode() == WebAssembly::END_BLOCK &&
770cf699b45SHeejin Ahn std::prev(B)->getOperand(0).getImm() == RetType;
771cf699b45SHeejin Ahn --B, ++E) {
772cf699b45SHeejin Ahn ToDelete.push_back(&*std::prev(B));
773cf699b45SHeejin Ahn ToDelete.push_back(&*E);
774cf699b45SHeejin Ahn }
775cf699b45SHeejin Ahn }
776cf699b45SHeejin Ahn }
777cf699b45SHeejin Ahn for (auto *MI : ToDelete) {
778cf699b45SHeejin Ahn if (MI->getOpcode() == WebAssembly::BLOCK)
779cf699b45SHeejin Ahn unregisterScope(MI);
780cf699b45SHeejin Ahn MI->eraseFromParent();
781cf699b45SHeejin Ahn }
782cf699b45SHeejin Ahn }
783cf699b45SHeejin Ahn
78461d5c76aSHeejin Ahn // When MBB is split into MBB and Split, we should unstackify defs in MBB that
78561d5c76aSHeejin Ahn // have their uses in Split.
unstackifyVRegsUsedInSplitBB(MachineBasicBlock & MBB,MachineBasicBlock & Split)786ed41945fSHeejin Ahn static void unstackifyVRegsUsedInSplitBB(MachineBasicBlock &MBB,
787ed41945fSHeejin Ahn MachineBasicBlock &Split) {
7881cc52357SHeejin Ahn MachineFunction &MF = *MBB.getParent();
7891cc52357SHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
7901cc52357SHeejin Ahn auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
7911cc52357SHeejin Ahn auto &MRI = MF.getRegInfo();
7921cc52357SHeejin Ahn
79361d5c76aSHeejin Ahn for (auto &MI : Split) {
79461d5c76aSHeejin Ahn for (auto &MO : MI.explicit_uses()) {
79561d5c76aSHeejin Ahn if (!MO.isReg() || Register::isPhysicalRegister(MO.getReg()))
79661d5c76aSHeejin Ahn continue;
79761d5c76aSHeejin Ahn if (MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg()))
79861d5c76aSHeejin Ahn if (Def->getParent() == &MBB)
79961d5c76aSHeejin Ahn MFI.unstackifyVReg(MO.getReg());
80061d5c76aSHeejin Ahn }
80161d5c76aSHeejin Ahn }
80283c26eaeSHeejin Ahn
80383c26eaeSHeejin Ahn // In RegStackify, when a register definition is used multiple times,
80483c26eaeSHeejin Ahn // Reg = INST ...
80583c26eaeSHeejin Ahn // INST ..., Reg, ...
80683c26eaeSHeejin Ahn // INST ..., Reg, ...
80783c26eaeSHeejin Ahn // INST ..., Reg, ...
80883c26eaeSHeejin Ahn //
80983c26eaeSHeejin Ahn // we introduce a TEE, which has the following form:
81083c26eaeSHeejin Ahn // DefReg = INST ...
81183c26eaeSHeejin Ahn // TeeReg, Reg = TEE_... DefReg
81283c26eaeSHeejin Ahn // INST ..., TeeReg, ...
81383c26eaeSHeejin Ahn // INST ..., Reg, ...
81483c26eaeSHeejin Ahn // INST ..., Reg, ...
81583c26eaeSHeejin Ahn // with DefReg and TeeReg stackified but Reg not stackified.
81683c26eaeSHeejin Ahn //
81783c26eaeSHeejin Ahn // But the invariant that TeeReg should be stackified can be violated while we
81883c26eaeSHeejin Ahn // unstackify registers in the split BB above. In this case, we convert TEEs
81983c26eaeSHeejin Ahn // into two COPYs. This COPY will be eventually eliminated in ExplicitLocals.
82083c26eaeSHeejin Ahn // DefReg = INST ...
82183c26eaeSHeejin Ahn // TeeReg = COPY DefReg
82283c26eaeSHeejin Ahn // Reg = COPY DefReg
82383c26eaeSHeejin Ahn // INST ..., TeeReg, ...
82483c26eaeSHeejin Ahn // INST ..., Reg, ...
82583c26eaeSHeejin Ahn // INST ..., Reg, ...
82685b4b21cSKazu Hirata for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
82783c26eaeSHeejin Ahn if (!WebAssembly::isTee(MI.getOpcode()))
82883c26eaeSHeejin Ahn continue;
82983c26eaeSHeejin Ahn Register TeeReg = MI.getOperand(0).getReg();
83083c26eaeSHeejin Ahn Register Reg = MI.getOperand(1).getReg();
83183c26eaeSHeejin Ahn Register DefReg = MI.getOperand(2).getReg();
83283c26eaeSHeejin Ahn if (!MFI.isVRegStackified(TeeReg)) {
83383c26eaeSHeejin Ahn // Now we are not using TEE anymore, so unstackify DefReg too
83483c26eaeSHeejin Ahn MFI.unstackifyVReg(DefReg);
835*beec3e8cSAlex Bradbury unsigned CopyOpc =
836*beec3e8cSAlex Bradbury WebAssembly::getCopyOpcodeForRegClass(MRI.getRegClass(DefReg));
83783c26eaeSHeejin Ahn BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), TeeReg)
83883c26eaeSHeejin Ahn .addReg(DefReg);
83983c26eaeSHeejin Ahn BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), Reg).addReg(DefReg);
84083c26eaeSHeejin Ahn MI.eraseFromParent();
84183c26eaeSHeejin Ahn }
84283c26eaeSHeejin Ahn }
84361d5c76aSHeejin Ahn }
84461d5c76aSHeejin Ahn
845ed41945fSHeejin Ahn // Wrap the given range of instruction with try-delegate. RangeBegin and
846ed41945fSHeejin Ahn // RangeEnd are inclusive.
addTryDelegate(MachineInstr * RangeBegin,MachineInstr * RangeEnd,MachineBasicBlock * DelegateDest)847ed41945fSHeejin Ahn void WebAssemblyCFGStackify::addTryDelegate(MachineInstr *RangeBegin,
848ed41945fSHeejin Ahn MachineInstr *RangeEnd,
849ed41945fSHeejin Ahn MachineBasicBlock *DelegateDest) {
850ed41945fSHeejin Ahn auto *BeginBB = RangeBegin->getParent();
851ed41945fSHeejin Ahn auto *EndBB = RangeEnd->getParent();
852ed41945fSHeejin Ahn MachineFunction &MF = *BeginBB->getParent();
853ed41945fSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
854ed41945fSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
855ed41945fSHeejin Ahn
856ed41945fSHeejin Ahn // Local expression tree before the first call of this range should go
857ed41945fSHeejin Ahn // after the nested TRY.
858ed41945fSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet;
859ed41945fSHeejin Ahn AfterSet.insert(RangeBegin);
860ed41945fSHeejin Ahn for (auto I = MachineBasicBlock::iterator(RangeBegin), E = BeginBB->begin();
861ed41945fSHeejin Ahn I != E; --I) {
862ed41945fSHeejin Ahn if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
863ed41945fSHeejin Ahn continue;
864ed41945fSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI))
865ed41945fSHeejin Ahn AfterSet.insert(&*std::prev(I));
866ed41945fSHeejin Ahn else
867ed41945fSHeejin Ahn break;
868ed41945fSHeejin Ahn }
869ed41945fSHeejin Ahn
870ed41945fSHeejin Ahn // Create the nested try instruction.
871ed41945fSHeejin Ahn auto TryPos = getLatestInsertPos(
872ed41945fSHeejin Ahn BeginBB, SmallPtrSet<const MachineInstr *, 4>(), AfterSet);
873ed41945fSHeejin Ahn MachineInstr *Try = BuildMI(*BeginBB, TryPos, RangeBegin->getDebugLoc(),
874ed41945fSHeejin Ahn TII.get(WebAssembly::TRY))
875ed41945fSHeejin Ahn .addImm(int64_t(WebAssembly::BlockType::Void));
876ed41945fSHeejin Ahn
877ed41945fSHeejin Ahn // Create a BB to insert the 'delegate' instruction.
878ed41945fSHeejin Ahn MachineBasicBlock *DelegateBB = MF.CreateMachineBasicBlock();
879ed41945fSHeejin Ahn // If the destination of 'delegate' is not the caller, adds the destination to
880ed41945fSHeejin Ahn // the BB's successors.
881ed41945fSHeejin Ahn if (DelegateDest != FakeCallerBB)
882ed41945fSHeejin Ahn DelegateBB->addSuccessor(DelegateDest);
883ed41945fSHeejin Ahn
884ed41945fSHeejin Ahn auto SplitPos = std::next(RangeEnd->getIterator());
885ed41945fSHeejin Ahn if (SplitPos == EndBB->end()) {
886ed41945fSHeejin Ahn // If the range's end instruction is at the end of the BB, insert the new
887ed41945fSHeejin Ahn // delegate BB after the current BB.
888ed41945fSHeejin Ahn MF.insert(std::next(EndBB->getIterator()), DelegateBB);
889ed41945fSHeejin Ahn EndBB->addSuccessor(DelegateBB);
890ed41945fSHeejin Ahn
891ed41945fSHeejin Ahn } else {
8929f770b36SHeejin Ahn // When the split pos is in the middle of a BB, we split the BB into two and
8939f770b36SHeejin Ahn // put the 'delegate' BB in between. We normally create a split BB and make
8949f770b36SHeejin Ahn // it a successor of the original BB (PostSplit == true), but in case the BB
8959f770b36SHeejin Ahn // is an EH pad and the split pos is before 'catch', we should preserve the
8969f770b36SHeejin Ahn // BB's property, including that it is an EH pad, in the later part of the
8979f770b36SHeejin Ahn // BB, where 'catch' is. In this case we set PostSplit to false.
8989f770b36SHeejin Ahn bool PostSplit = true;
8999f770b36SHeejin Ahn if (EndBB->isEHPad()) {
9009f770b36SHeejin Ahn for (auto I = MachineBasicBlock::iterator(SplitPos), E = EndBB->end();
9019f770b36SHeejin Ahn I != E; ++I) {
9029f770b36SHeejin Ahn if (WebAssembly::isCatch(I->getOpcode())) {
9039f770b36SHeejin Ahn PostSplit = false;
9049f770b36SHeejin Ahn break;
9059f770b36SHeejin Ahn }
9069f770b36SHeejin Ahn }
9079f770b36SHeejin Ahn }
9089f770b36SHeejin Ahn
9099f770b36SHeejin Ahn MachineBasicBlock *PreBB = nullptr, *PostBB = nullptr;
9109f770b36SHeejin Ahn if (PostSplit) {
911ed41945fSHeejin Ahn // If the range's end instruction is in the middle of the BB, we split the
912ed41945fSHeejin Ahn // BB into two and insert the delegate BB in between.
913ed41945fSHeejin Ahn // - Before:
914ed41945fSHeejin Ahn // bb:
915ed41945fSHeejin Ahn // range_end
916ed41945fSHeejin Ahn // other_insts
917ed41945fSHeejin Ahn //
918ed41945fSHeejin Ahn // - After:
919ed41945fSHeejin Ahn // pre_bb: (previous 'bb')
920ed41945fSHeejin Ahn // range_end
921ed41945fSHeejin Ahn // delegate_bb: (new)
922ed41945fSHeejin Ahn // delegate
923ed41945fSHeejin Ahn // post_bb: (new)
924ed41945fSHeejin Ahn // other_insts
9259f770b36SHeejin Ahn PreBB = EndBB;
9269f770b36SHeejin Ahn PostBB = MF.CreateMachineBasicBlock();
927ed41945fSHeejin Ahn MF.insert(std::next(PreBB->getIterator()), PostBB);
928ed41945fSHeejin Ahn MF.insert(std::next(PreBB->getIterator()), DelegateBB);
929ed41945fSHeejin Ahn PostBB->splice(PostBB->end(), PreBB, SplitPos, PreBB->end());
930ed41945fSHeejin Ahn PostBB->transferSuccessors(PreBB);
9319f770b36SHeejin Ahn } else {
9329f770b36SHeejin Ahn // - Before:
9339f770b36SHeejin Ahn // ehpad:
9349f770b36SHeejin Ahn // range_end
9359f770b36SHeejin Ahn // catch
9369f770b36SHeejin Ahn // ...
9379f770b36SHeejin Ahn //
9389f770b36SHeejin Ahn // - After:
9399f770b36SHeejin Ahn // pre_bb: (new)
9409f770b36SHeejin Ahn // range_end
9419f770b36SHeejin Ahn // delegate_bb: (new)
9429f770b36SHeejin Ahn // delegate
9439f770b36SHeejin Ahn // post_bb: (previous 'ehpad')
9449f770b36SHeejin Ahn // catch
9459f770b36SHeejin Ahn // ...
9469f770b36SHeejin Ahn assert(EndBB->isEHPad());
9479f770b36SHeejin Ahn PreBB = MF.CreateMachineBasicBlock();
9489f770b36SHeejin Ahn PostBB = EndBB;
9499f770b36SHeejin Ahn MF.insert(PostBB->getIterator(), PreBB);
9509f770b36SHeejin Ahn MF.insert(PostBB->getIterator(), DelegateBB);
9519f770b36SHeejin Ahn PreBB->splice(PreBB->end(), PostBB, PostBB->begin(), SplitPos);
9529f770b36SHeejin Ahn // We don't need to transfer predecessors of the EH pad to 'PreBB',
9539f770b36SHeejin Ahn // because an EH pad's predecessors are all through unwind edges and they
9549f770b36SHeejin Ahn // should still unwind to the EH pad, not PreBB.
9559f770b36SHeejin Ahn }
956ed41945fSHeejin Ahn unstackifyVRegsUsedInSplitBB(*PreBB, *PostBB);
957ed41945fSHeejin Ahn PreBB->addSuccessor(DelegateBB);
958ed41945fSHeejin Ahn PreBB->addSuccessor(PostBB);
959ed41945fSHeejin Ahn }
960ed41945fSHeejin Ahn
961ed41945fSHeejin Ahn // Add 'delegate' instruction in the delegate BB created above.
962ed41945fSHeejin Ahn MachineInstr *Delegate = BuildMI(DelegateBB, RangeEnd->getDebugLoc(),
963ed41945fSHeejin Ahn TII.get(WebAssembly::DELEGATE))
964ed41945fSHeejin Ahn .addMBB(DelegateDest);
965ed41945fSHeejin Ahn registerTryScope(Try, Delegate, nullptr);
966ed41945fSHeejin Ahn }
967ed41945fSHeejin Ahn
fixCallUnwindMismatches(MachineFunction & MF)968ed41945fSHeejin Ahn bool WebAssemblyCFGStackify::fixCallUnwindMismatches(MachineFunction &MF) {
969ed41945fSHeejin Ahn // Linearizing the control flow by placing TRY / END_TRY markers can create
970ed41945fSHeejin Ahn // mismatches in unwind destinations for throwing instructions, such as calls.
971ed41945fSHeejin Ahn //
972ed41945fSHeejin Ahn // We use the 'delegate' instruction to fix the unwind mismatches. 'delegate'
973ed41945fSHeejin Ahn // instruction delegates an exception to an outer 'catch'. It can target not
974ed41945fSHeejin Ahn // only 'catch' but all block-like structures including another 'delegate',
975ed41945fSHeejin Ahn // but with slightly different semantics than branches. When it targets a
976ed41945fSHeejin Ahn // 'catch', it will delegate the exception to that catch. It is being
977ed41945fSHeejin Ahn // discussed how to define the semantics when 'delegate''s target is a non-try
978ed41945fSHeejin Ahn // block: it will either be a validation failure or it will target the next
979ed41945fSHeejin Ahn // outer try-catch. But anyway our LLVM backend currently does not generate
980ed41945fSHeejin Ahn // such code. The example below illustrates where the 'delegate' instruction
981ed41945fSHeejin Ahn // in the middle will delegate the exception to, depending on the value of N.
982ed41945fSHeejin Ahn // try
983ed41945fSHeejin Ahn // try
984ed41945fSHeejin Ahn // block
985ed41945fSHeejin Ahn // try
986ed41945fSHeejin Ahn // try
987ed41945fSHeejin Ahn // call @foo
988ed41945fSHeejin Ahn // delegate N ;; Where will this delegate to?
989ed41945fSHeejin Ahn // catch ;; N == 0
990ed41945fSHeejin Ahn // end
991ed41945fSHeejin Ahn // end ;; N == 1 (invalid; will not be generated)
992ed41945fSHeejin Ahn // delegate ;; N == 2
993ed41945fSHeejin Ahn // catch ;; N == 3
994ed41945fSHeejin Ahn // end
995ed41945fSHeejin Ahn // ;; N == 4 (to caller)
996ed41945fSHeejin Ahn
997ed41945fSHeejin Ahn // 1. When an instruction may throw, but the EH pad it will unwind to can be
998ed41945fSHeejin Ahn // different from the original CFG.
999ed41945fSHeejin Ahn //
1000ed41945fSHeejin Ahn // Example: we have the following CFG:
1001ed41945fSHeejin Ahn // bb0:
1002ed41945fSHeejin Ahn // call @foo ; if it throws, unwind to bb2
1003ed41945fSHeejin Ahn // bb1:
1004ed41945fSHeejin Ahn // call @bar ; if it throws, unwind to bb3
1005ed41945fSHeejin Ahn // bb2 (ehpad):
1006ed41945fSHeejin Ahn // catch
1007ed41945fSHeejin Ahn // ...
1008ed41945fSHeejin Ahn // bb3 (ehpad)
1009ed41945fSHeejin Ahn // catch
1010ed41945fSHeejin Ahn // ...
1011ed41945fSHeejin Ahn //
1012ed41945fSHeejin Ahn // And the CFG is sorted in this order. Then after placing TRY markers, it
1013ed41945fSHeejin Ahn // will look like: (BB markers are omitted)
1014ed41945fSHeejin Ahn // try
1015ed41945fSHeejin Ahn // try
1016ed41945fSHeejin Ahn // call @foo
1017ed41945fSHeejin Ahn // call @bar ;; if it throws, unwind to bb3
1018ed41945fSHeejin Ahn // catch ;; ehpad (bb2)
1019ed41945fSHeejin Ahn // ...
1020ed41945fSHeejin Ahn // end_try
1021ed41945fSHeejin Ahn // catch ;; ehpad (bb3)
1022ed41945fSHeejin Ahn // ...
1023ed41945fSHeejin Ahn // end_try
1024ed41945fSHeejin Ahn //
1025ed41945fSHeejin Ahn // Now if bar() throws, it is going to end up ip in bb2, not bb3, where it
1026ed41945fSHeejin Ahn // is supposed to end up. We solve this problem by wrapping the mismatching
1027ed41945fSHeejin Ahn // call with an inner try-delegate that rethrows the exception to the right
1028ed41945fSHeejin Ahn // 'catch'.
1029ed41945fSHeejin Ahn //
1030ed41945fSHeejin Ahn // try
1031ed41945fSHeejin Ahn // try
1032ed41945fSHeejin Ahn // call @foo
1033ed41945fSHeejin Ahn // try ;; (new)
1034ed41945fSHeejin Ahn // call @bar
1035ed41945fSHeejin Ahn // delegate 1 (bb3) ;; (new)
1036ed41945fSHeejin Ahn // catch ;; ehpad (bb2)
1037ed41945fSHeejin Ahn // ...
1038ed41945fSHeejin Ahn // end_try
1039ed41945fSHeejin Ahn // catch ;; ehpad (bb3)
1040ed41945fSHeejin Ahn // ...
1041ed41945fSHeejin Ahn // end_try
1042ed41945fSHeejin Ahn //
1043ed41945fSHeejin Ahn // ---
1044ed41945fSHeejin Ahn // 2. The same as 1, but in this case an instruction unwinds to a caller
1045ed41945fSHeejin Ahn // function and not another EH pad.
1046ed41945fSHeejin Ahn //
1047ed41945fSHeejin Ahn // Example: we have the following CFG:
1048ed41945fSHeejin Ahn // bb0:
1049ed41945fSHeejin Ahn // call @foo ; if it throws, unwind to bb2
1050ed41945fSHeejin Ahn // bb1:
1051ed41945fSHeejin Ahn // call @bar ; if it throws, unwind to caller
1052ed41945fSHeejin Ahn // bb2 (ehpad):
1053ed41945fSHeejin Ahn // catch
1054ed41945fSHeejin Ahn // ...
1055ed41945fSHeejin Ahn //
1056ed41945fSHeejin Ahn // And the CFG is sorted in this order. Then after placing TRY markers, it
1057ed41945fSHeejin Ahn // will look like:
1058ed41945fSHeejin Ahn // try
1059ed41945fSHeejin Ahn // call @foo
1060ed41945fSHeejin Ahn // call @bar ;; if it throws, unwind to caller
1061ed41945fSHeejin Ahn // catch ;; ehpad (bb2)
1062ed41945fSHeejin Ahn // ...
1063ed41945fSHeejin Ahn // end_try
1064ed41945fSHeejin Ahn //
1065ed41945fSHeejin Ahn // Now if bar() throws, it is going to end up ip in bb2, when it is supposed
1066ed41945fSHeejin Ahn // throw up to the caller. We solve this problem in the same way, but in this
1067ed41945fSHeejin Ahn // case 'delegate's immediate argument is the number of block depths + 1,
1068ed41945fSHeejin Ahn // which means it rethrows to the caller.
1069ed41945fSHeejin Ahn // try
1070ed41945fSHeejin Ahn // call @foo
1071ed41945fSHeejin Ahn // try ;; (new)
1072ed41945fSHeejin Ahn // call @bar
1073ed41945fSHeejin Ahn // delegate 1 (caller) ;; (new)
1074ed41945fSHeejin Ahn // catch ;; ehpad (bb2)
1075ed41945fSHeejin Ahn // ...
1076ed41945fSHeejin Ahn // end_try
1077ed41945fSHeejin Ahn //
1078ed41945fSHeejin Ahn // Before rewriteDepthImmediates, delegate's argument is a BB. In case of the
1079ed41945fSHeejin Ahn // caller, it will take a fake BB generated by getFakeCallerBlock(), which
1080ed41945fSHeejin Ahn // will be converted to a correct immediate argument later.
1081ed41945fSHeejin Ahn //
1082ed41945fSHeejin Ahn // In case there are multiple calls in a BB that may throw to the caller, they
1083ed41945fSHeejin Ahn // can be wrapped together in one nested try-delegate scope. (In 1, this
1084ed41945fSHeejin Ahn // couldn't happen, because may-throwing instruction there had an unwind
1085ed41945fSHeejin Ahn // destination, i.e., it was an invoke before, and there could be only one
1086ed41945fSHeejin Ahn // invoke within a BB.)
1087ed41945fSHeejin Ahn
1088ed41945fSHeejin Ahn SmallVector<const MachineBasicBlock *, 8> EHPadStack;
1089ed41945fSHeejin Ahn // Range of intructions to be wrapped in a new nested try/catch. A range
1090ed41945fSHeejin Ahn // exists in a single BB and does not span multiple BBs.
1091ed41945fSHeejin Ahn using TryRange = std::pair<MachineInstr *, MachineInstr *>;
1092ed41945fSHeejin Ahn // In original CFG, <unwind destination BB, a vector of try ranges>
1093ed41945fSHeejin Ahn DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> UnwindDestToTryRanges;
1094ed41945fSHeejin Ahn
1095ed41945fSHeejin Ahn // Gather possibly throwing calls (i.e., previously invokes) whose current
1096ed41945fSHeejin Ahn // unwind destination is not the same as the original CFG. (Case 1)
1097ed41945fSHeejin Ahn
1098ed41945fSHeejin Ahn for (auto &MBB : reverse(MF)) {
1099ed41945fSHeejin Ahn bool SeenThrowableInstInBB = false;
1100ed41945fSHeejin Ahn for (auto &MI : reverse(MBB)) {
1101ed41945fSHeejin Ahn if (MI.getOpcode() == WebAssembly::TRY)
1102ed41945fSHeejin Ahn EHPadStack.pop_back();
1103ed41945fSHeejin Ahn else if (WebAssembly::isCatch(MI.getOpcode()))
1104ed41945fSHeejin Ahn EHPadStack.push_back(MI.getParent());
1105ed41945fSHeejin Ahn
1106ed41945fSHeejin Ahn // In this loop we only gather calls that have an EH pad to unwind. So
1107ed41945fSHeejin Ahn // there will be at most 1 such call (= invoke) in a BB, so after we've
1108ed41945fSHeejin Ahn // seen one, we can skip the rest of BB. Also if MBB has no EH pad
1109ed41945fSHeejin Ahn // successor or MI does not throw, this is not an invoke.
1110ed41945fSHeejin Ahn if (SeenThrowableInstInBB || !MBB.hasEHPadSuccessor() ||
1111ed41945fSHeejin Ahn !WebAssembly::mayThrow(MI))
1112ed41945fSHeejin Ahn continue;
1113ed41945fSHeejin Ahn SeenThrowableInstInBB = true;
1114ed41945fSHeejin Ahn
1115ed41945fSHeejin Ahn // If the EH pad on the stack top is where this instruction should unwind
1116ed41945fSHeejin Ahn // next, we're good.
1117ed41945fSHeejin Ahn MachineBasicBlock *UnwindDest = getFakeCallerBlock(MF);
1118ed41945fSHeejin Ahn for (auto *Succ : MBB.successors()) {
1119ed41945fSHeejin Ahn // Even though semantically a BB can have multiple successors in case an
1120ed41945fSHeejin Ahn // exception is not caught by a catchpad, in our backend implementation
1121ed41945fSHeejin Ahn // it is guaranteed that a BB can have at most one EH pad successor. For
1122ed41945fSHeejin Ahn // details, refer to comments in findWasmUnwindDestinations function in
1123ed41945fSHeejin Ahn // SelectionDAGBuilder.cpp.
1124ed41945fSHeejin Ahn if (Succ->isEHPad()) {
1125ed41945fSHeejin Ahn UnwindDest = Succ;
1126ed41945fSHeejin Ahn break;
1127ed41945fSHeejin Ahn }
1128ed41945fSHeejin Ahn }
1129ed41945fSHeejin Ahn if (EHPadStack.back() == UnwindDest)
1130ed41945fSHeejin Ahn continue;
1131ed41945fSHeejin Ahn
1132ed41945fSHeejin Ahn // Include EH_LABELs in the range before and afer the invoke
1133ed41945fSHeejin Ahn MachineInstr *RangeBegin = &MI, *RangeEnd = &MI;
1134ed41945fSHeejin Ahn if (RangeBegin->getIterator() != MBB.begin() &&
1135ed41945fSHeejin Ahn std::prev(RangeBegin->getIterator())->isEHLabel())
1136ed41945fSHeejin Ahn RangeBegin = &*std::prev(RangeBegin->getIterator());
1137ed41945fSHeejin Ahn if (std::next(RangeEnd->getIterator()) != MBB.end() &&
1138ed41945fSHeejin Ahn std::next(RangeEnd->getIterator())->isEHLabel())
1139ed41945fSHeejin Ahn RangeEnd = &*std::next(RangeEnd->getIterator());
1140ed41945fSHeejin Ahn
1141ed41945fSHeejin Ahn // If not, record the range.
1142ed41945fSHeejin Ahn UnwindDestToTryRanges[UnwindDest].push_back(
1143ed41945fSHeejin Ahn TryRange(RangeBegin, RangeEnd));
1144ed41945fSHeejin Ahn LLVM_DEBUG(dbgs() << "- Call unwind mismatch: MBB = " << MBB.getName()
1145ed41945fSHeejin Ahn << "\nCall = " << MI
1146ed41945fSHeejin Ahn << "\nOriginal dest = " << UnwindDest->getName()
1147ed41945fSHeejin Ahn << " Current dest = " << EHPadStack.back()->getName()
1148ed41945fSHeejin Ahn << "\n\n");
1149ed41945fSHeejin Ahn }
1150ed41945fSHeejin Ahn }
1151ed41945fSHeejin Ahn
1152ed41945fSHeejin Ahn assert(EHPadStack.empty());
1153ed41945fSHeejin Ahn
1154ed41945fSHeejin Ahn // Gather possibly throwing calls that are supposed to unwind up to the caller
1155ed41945fSHeejin Ahn // if they throw, but currently unwind to an incorrect destination. Unlike the
1156ed41945fSHeejin Ahn // loop above, there can be multiple calls within a BB that unwind to the
1157ed41945fSHeejin Ahn // caller, which we should group together in a range. (Case 2)
1158ed41945fSHeejin Ahn
1159ed41945fSHeejin Ahn MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; // inclusive
1160ed41945fSHeejin Ahn
1161ed41945fSHeejin Ahn // Record the range.
1162ed41945fSHeejin Ahn auto RecordCallerMismatchRange = [&](const MachineBasicBlock *CurrentDest) {
1163ed41945fSHeejin Ahn UnwindDestToTryRanges[getFakeCallerBlock(MF)].push_back(
1164ed41945fSHeejin Ahn TryRange(RangeBegin, RangeEnd));
1165ed41945fSHeejin Ahn LLVM_DEBUG(dbgs() << "- Call unwind mismatch: MBB = "
1166ed41945fSHeejin Ahn << RangeBegin->getParent()->getName()
1167ed41945fSHeejin Ahn << "\nRange begin = " << *RangeBegin
1168ed41945fSHeejin Ahn << "Range end = " << *RangeEnd
1169ed41945fSHeejin Ahn << "\nOriginal dest = caller Current dest = "
1170ed41945fSHeejin Ahn << CurrentDest->getName() << "\n\n");
1171ed41945fSHeejin Ahn RangeBegin = RangeEnd = nullptr; // Reset range pointers
1172ed41945fSHeejin Ahn };
1173ed41945fSHeejin Ahn
1174ed41945fSHeejin Ahn for (auto &MBB : reverse(MF)) {
1175ed41945fSHeejin Ahn bool SeenThrowableInstInBB = false;
1176ed41945fSHeejin Ahn for (auto &MI : reverse(MBB)) {
1177ed41945fSHeejin Ahn bool MayThrow = WebAssembly::mayThrow(MI);
1178ed41945fSHeejin Ahn
1179ed41945fSHeejin Ahn // If MBB has an EH pad successor and this is the last instruction that
1180ed41945fSHeejin Ahn // may throw, this instruction unwinds to the EH pad and not to the
1181ed41945fSHeejin Ahn // caller.
1182da01a9dbSHeejin Ahn if (MBB.hasEHPadSuccessor() && MayThrow && !SeenThrowableInstInBB)
1183ed41945fSHeejin Ahn SeenThrowableInstInBB = true;
1184ed41945fSHeejin Ahn
1185ed41945fSHeejin Ahn // We wrap up the current range when we see a marker even if we haven't
1186ed41945fSHeejin Ahn // finished a BB.
1187da01a9dbSHeejin Ahn else if (RangeEnd && WebAssembly::isMarker(MI.getOpcode()))
1188ed41945fSHeejin Ahn RecordCallerMismatchRange(EHPadStack.back());
1189ed41945fSHeejin Ahn
1190ed41945fSHeejin Ahn // If EHPadStack is empty, that means it correctly unwinds to the caller
1191ed41945fSHeejin Ahn // if it throws, so we're good. If MI does not throw, we're good too.
1192da01a9dbSHeejin Ahn else if (EHPadStack.empty() || !MayThrow) {
1193da01a9dbSHeejin Ahn }
1194ed41945fSHeejin Ahn
1195ed41945fSHeejin Ahn // We found an instruction that unwinds to the caller but currently has an
1196ed41945fSHeejin Ahn // incorrect unwind destination. Create a new range or increment the
1197ed41945fSHeejin Ahn // currently existing range.
1198da01a9dbSHeejin Ahn else {
1199ed41945fSHeejin Ahn if (!RangeEnd)
1200ed41945fSHeejin Ahn RangeBegin = RangeEnd = &MI;
1201ed41945fSHeejin Ahn else
1202ed41945fSHeejin Ahn RangeBegin = &MI;
1203ed41945fSHeejin Ahn }
1204ed41945fSHeejin Ahn
1205da01a9dbSHeejin Ahn // Update EHPadStack.
1206da01a9dbSHeejin Ahn if (MI.getOpcode() == WebAssembly::TRY)
1207da01a9dbSHeejin Ahn EHPadStack.pop_back();
1208da01a9dbSHeejin Ahn else if (WebAssembly::isCatch(MI.getOpcode()))
1209da01a9dbSHeejin Ahn EHPadStack.push_back(MI.getParent());
1210da01a9dbSHeejin Ahn }
1211da01a9dbSHeejin Ahn
1212ed41945fSHeejin Ahn if (RangeEnd)
1213ed41945fSHeejin Ahn RecordCallerMismatchRange(EHPadStack.back());
1214ed41945fSHeejin Ahn }
1215ed41945fSHeejin Ahn
1216ed41945fSHeejin Ahn assert(EHPadStack.empty());
1217ed41945fSHeejin Ahn
1218ed41945fSHeejin Ahn // We don't have any unwind destination mismatches to resolve.
1219ed41945fSHeejin Ahn if (UnwindDestToTryRanges.empty())
1220ed41945fSHeejin Ahn return false;
1221ed41945fSHeejin Ahn
1222ed41945fSHeejin Ahn // Now we fix the mismatches by wrapping calls with inner try-delegates.
1223ed41945fSHeejin Ahn for (auto &P : UnwindDestToTryRanges) {
1224ed41945fSHeejin Ahn NumCallUnwindMismatches += P.second.size();
1225ed41945fSHeejin Ahn MachineBasicBlock *UnwindDest = P.first;
1226ed41945fSHeejin Ahn auto &TryRanges = P.second;
1227ed41945fSHeejin Ahn
1228ed41945fSHeejin Ahn for (auto Range : TryRanges) {
1229ed41945fSHeejin Ahn MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr;
1230ed41945fSHeejin Ahn std::tie(RangeBegin, RangeEnd) = Range;
1231ed41945fSHeejin Ahn auto *MBB = RangeBegin->getParent();
1232ed41945fSHeejin Ahn
1233ed41945fSHeejin Ahn // If this BB has an EH pad successor, i.e., ends with an 'invoke', now we
1234ed41945fSHeejin Ahn // are going to wrap the invoke with try-delegate, making the 'delegate'
1235ed41945fSHeejin Ahn // BB the new successor instead, so remove the EH pad succesor here. The
1236ed41945fSHeejin Ahn // BB may not have an EH pad successor if calls in this BB throw to the
1237ed41945fSHeejin Ahn // caller.
1238ed41945fSHeejin Ahn MachineBasicBlock *EHPad = nullptr;
1239ed41945fSHeejin Ahn for (auto *Succ : MBB->successors()) {
1240ed41945fSHeejin Ahn if (Succ->isEHPad()) {
1241ed41945fSHeejin Ahn EHPad = Succ;
1242ed41945fSHeejin Ahn break;
1243ed41945fSHeejin Ahn }
1244ed41945fSHeejin Ahn }
1245ed41945fSHeejin Ahn if (EHPad)
1246ed41945fSHeejin Ahn MBB->removeSuccessor(EHPad);
1247ed41945fSHeejin Ahn
1248ed41945fSHeejin Ahn addTryDelegate(RangeBegin, RangeEnd, UnwindDest);
1249ed41945fSHeejin Ahn }
1250ed41945fSHeejin Ahn }
1251ed41945fSHeejin Ahn
1252ed41945fSHeejin Ahn return true;
1253ed41945fSHeejin Ahn }
1254ed41945fSHeejin Ahn
fixCatchUnwindMismatches(MachineFunction & MF)1255ed41945fSHeejin Ahn bool WebAssemblyCFGStackify::fixCatchUnwindMismatches(MachineFunction &MF) {
12569f770b36SHeejin Ahn // There is another kind of unwind destination mismatches besides call unwind
12579f770b36SHeejin Ahn // mismatches, which we will call "catch unwind mismatches". See this example
12589f770b36SHeejin Ahn // after the marker placement:
12599f770b36SHeejin Ahn // try
12609f770b36SHeejin Ahn // try
12619f770b36SHeejin Ahn // call @foo
12629f770b36SHeejin Ahn // catch __cpp_exception ;; ehpad A (next unwind dest: caller)
12639f770b36SHeejin Ahn // ...
12649f770b36SHeejin Ahn // end_try
12659f770b36SHeejin Ahn // catch_all ;; ehpad B
12669f770b36SHeejin Ahn // ...
12679f770b36SHeejin Ahn // end_try
12689f770b36SHeejin Ahn //
12699f770b36SHeejin Ahn // 'call @foo's unwind destination is the ehpad A. But suppose 'call @foo'
12709f770b36SHeejin Ahn // throws a foreign exception that is not caught by ehpad A, and its next
12719f770b36SHeejin Ahn // destination should be the caller. But after control flow linearization,
12729f770b36SHeejin Ahn // another EH pad can be placed in between (e.g. ehpad B here), making the
12739f770b36SHeejin Ahn // next unwind destination incorrect. In this case, the foreign exception
12749f770b36SHeejin Ahn // will instead go to ehpad B and will be caught there instead. In this
12759f770b36SHeejin Ahn // example the correct next unwind destination is the caller, but it can be
12769f770b36SHeejin Ahn // another outer catch in other cases.
12779f770b36SHeejin Ahn //
12789f770b36SHeejin Ahn // There is no specific 'call' or 'throw' instruction to wrap with a
12799f770b36SHeejin Ahn // try-delegate, so we wrap the whole try-catch-end with a try-delegate and
12809f770b36SHeejin Ahn // make it rethrow to the right destination, as in the example below:
12819f770b36SHeejin Ahn // try
12829f770b36SHeejin Ahn // try ;; (new)
12839f770b36SHeejin Ahn // try
12849f770b36SHeejin Ahn // call @foo
12859f770b36SHeejin Ahn // catch __cpp_exception ;; ehpad A (next unwind dest: caller)
12869f770b36SHeejin Ahn // ...
12879f770b36SHeejin Ahn // end_try
12889f770b36SHeejin Ahn // delegate 1 (caller) ;; (new)
12899f770b36SHeejin Ahn // catch_all ;; ehpad B
12909f770b36SHeejin Ahn // ...
12919f770b36SHeejin Ahn // end_try
12929f770b36SHeejin Ahn
12939f770b36SHeejin Ahn const auto *EHInfo = MF.getWasmEHFuncInfo();
12949f770b36SHeejin Ahn SmallVector<const MachineBasicBlock *, 8> EHPadStack;
12959f770b36SHeejin Ahn // For EH pads that have catch unwind mismatches, a map of <EH pad, its
12969f770b36SHeejin Ahn // correct unwind destination>.
12979f770b36SHeejin Ahn DenseMap<MachineBasicBlock *, MachineBasicBlock *> EHPadToUnwindDest;
12989f770b36SHeejin Ahn
12999f770b36SHeejin Ahn for (auto &MBB : reverse(MF)) {
13009f770b36SHeejin Ahn for (auto &MI : reverse(MBB)) {
13019f770b36SHeejin Ahn if (MI.getOpcode() == WebAssembly::TRY)
13029f770b36SHeejin Ahn EHPadStack.pop_back();
13039f770b36SHeejin Ahn else if (MI.getOpcode() == WebAssembly::DELEGATE)
13049f770b36SHeejin Ahn EHPadStack.push_back(&MBB);
13059f770b36SHeejin Ahn else if (WebAssembly::isCatch(MI.getOpcode())) {
13069f770b36SHeejin Ahn auto *EHPad = &MBB;
13079f770b36SHeejin Ahn
13089f770b36SHeejin Ahn // catch_all always catches an exception, so we don't need to do
13099f770b36SHeejin Ahn // anything
13109f770b36SHeejin Ahn if (MI.getOpcode() == WebAssembly::CATCH_ALL) {
13119f770b36SHeejin Ahn }
13129f770b36SHeejin Ahn
13139f770b36SHeejin Ahn // This can happen when the unwind dest was removed during the
13149f770b36SHeejin Ahn // optimization, e.g. because it was unreachable.
1315a08e609dSHeejin Ahn else if (EHPadStack.empty() && EHInfo->hasUnwindDest(EHPad)) {
13169f770b36SHeejin Ahn LLVM_DEBUG(dbgs() << "EHPad (" << EHPad->getName()
13179f770b36SHeejin Ahn << "'s unwind destination does not exist anymore"
13189f770b36SHeejin Ahn << "\n\n");
13199f770b36SHeejin Ahn }
13209f770b36SHeejin Ahn
13219f770b36SHeejin Ahn // The EHPad's next unwind destination is the caller, but we incorrectly
13229f770b36SHeejin Ahn // unwind to another EH pad.
1323a08e609dSHeejin Ahn else if (!EHPadStack.empty() && !EHInfo->hasUnwindDest(EHPad)) {
13249f770b36SHeejin Ahn EHPadToUnwindDest[EHPad] = getFakeCallerBlock(MF);
13259f770b36SHeejin Ahn LLVM_DEBUG(dbgs()
13269f770b36SHeejin Ahn << "- Catch unwind mismatch:\nEHPad = " << EHPad->getName()
13279f770b36SHeejin Ahn << " Original dest = caller Current dest = "
13289f770b36SHeejin Ahn << EHPadStack.back()->getName() << "\n\n");
13299f770b36SHeejin Ahn }
13309f770b36SHeejin Ahn
13319f770b36SHeejin Ahn // The EHPad's next unwind destination is an EH pad, whereas we
13329f770b36SHeejin Ahn // incorrectly unwind to another EH pad.
1333a08e609dSHeejin Ahn else if (!EHPadStack.empty() && EHInfo->hasUnwindDest(EHPad)) {
1334a08e609dSHeejin Ahn auto *UnwindDest = EHInfo->getUnwindDest(EHPad);
13359f770b36SHeejin Ahn if (EHPadStack.back() != UnwindDest) {
13369f770b36SHeejin Ahn EHPadToUnwindDest[EHPad] = UnwindDest;
13379f770b36SHeejin Ahn LLVM_DEBUG(dbgs() << "- Catch unwind mismatch:\nEHPad = "
13389f770b36SHeejin Ahn << EHPad->getName() << " Original dest = "
13399f770b36SHeejin Ahn << UnwindDest->getName() << " Current dest = "
13409f770b36SHeejin Ahn << EHPadStack.back()->getName() << "\n\n");
13419f770b36SHeejin Ahn }
13429f770b36SHeejin Ahn }
13439f770b36SHeejin Ahn
13449f770b36SHeejin Ahn EHPadStack.push_back(EHPad);
13459f770b36SHeejin Ahn }
13469f770b36SHeejin Ahn }
13479f770b36SHeejin Ahn }
13489f770b36SHeejin Ahn
13499f770b36SHeejin Ahn assert(EHPadStack.empty());
13509f770b36SHeejin Ahn if (EHPadToUnwindDest.empty())
1351c4ac74fbSHeejin Ahn return false;
13529f770b36SHeejin Ahn NumCatchUnwindMismatches += EHPadToUnwindDest.size();
1353d8b3dc5aSHeejin Ahn SmallPtrSet<MachineBasicBlock *, 4> NewEndTryBBs;
13549f770b36SHeejin Ahn
13559f770b36SHeejin Ahn for (auto &P : EHPadToUnwindDest) {
13569f770b36SHeejin Ahn MachineBasicBlock *EHPad = P.first;
13579f770b36SHeejin Ahn MachineBasicBlock *UnwindDest = P.second;
13589f770b36SHeejin Ahn MachineInstr *Try = EHPadToTry[EHPad];
13599f770b36SHeejin Ahn MachineInstr *EndTry = BeginToEnd[Try];
13609f770b36SHeejin Ahn addTryDelegate(Try, EndTry, UnwindDest);
1361d8b3dc5aSHeejin Ahn NewEndTryBBs.insert(EndTry->getParent());
1362f47a654aSHeejin Ahn }
1363f47a654aSHeejin Ahn
1364f47a654aSHeejin Ahn // Adding a try-delegate wrapping an existing try-catch-end can make existing
1365f47a654aSHeejin Ahn // branch destination BBs invalid. For example,
1366f47a654aSHeejin Ahn //
1367f47a654aSHeejin Ahn // - Before:
1368f47a654aSHeejin Ahn // bb0:
1369f47a654aSHeejin Ahn // block
1370f47a654aSHeejin Ahn // br bb3
1371f47a654aSHeejin Ahn // bb1:
1372f47a654aSHeejin Ahn // try
1373f47a654aSHeejin Ahn // ...
1374f47a654aSHeejin Ahn // bb2: (ehpad)
1375f47a654aSHeejin Ahn // catch
1376f47a654aSHeejin Ahn // bb3:
1377f47a654aSHeejin Ahn // end_try
1378f47a654aSHeejin Ahn // end_block ;; 'br bb3' targets here
1379f47a654aSHeejin Ahn //
1380f47a654aSHeejin Ahn // Suppose this try-catch-end has a catch unwind mismatch, so we need to wrap
1381f47a654aSHeejin Ahn // this with a try-delegate. Then this becomes:
1382f47a654aSHeejin Ahn //
1383f47a654aSHeejin Ahn // - After:
1384f47a654aSHeejin Ahn // bb0:
1385f47a654aSHeejin Ahn // block
1386f47a654aSHeejin Ahn // br bb3 ;; invalid destination!
1387f47a654aSHeejin Ahn // bb1:
1388f47a654aSHeejin Ahn // try ;; (new instruction)
1389f47a654aSHeejin Ahn // try
1390f47a654aSHeejin Ahn // ...
1391f47a654aSHeejin Ahn // bb2: (ehpad)
1392f47a654aSHeejin Ahn // catch
1393f47a654aSHeejin Ahn // bb3:
1394f47a654aSHeejin Ahn // end_try ;; 'br bb3' still incorrectly targets here!
1395f47a654aSHeejin Ahn // delegate_bb: ;; (new BB)
1396f47a654aSHeejin Ahn // delegate ;; (new instruction)
1397f47a654aSHeejin Ahn // split_bb: ;; (new BB)
1398f47a654aSHeejin Ahn // end_block
1399f47a654aSHeejin Ahn //
1400f47a654aSHeejin Ahn // Now 'br bb3' incorrectly branches to an inner scope.
1401f47a654aSHeejin Ahn //
1402f47a654aSHeejin Ahn // As we can see in this case, when branches target a BB that has both
1403f47a654aSHeejin Ahn // 'end_try' and 'end_block' and the BB is split to insert a 'delegate', we
1404f47a654aSHeejin Ahn // have to remap existing branch destinations so that they target not the
1405d8b3dc5aSHeejin Ahn // 'end_try' BB but the new 'end_block' BB. There can be multiple 'delegate's
1406d8b3dc5aSHeejin Ahn // in between, so we try to find the next BB with 'end_block' instruction. In
1407d8b3dc5aSHeejin Ahn // this example, the 'br bb3' instruction should be remapped to 'br split_bb'.
1408f47a654aSHeejin Ahn for (auto &MBB : MF) {
1409f47a654aSHeejin Ahn for (auto &MI : MBB) {
1410f47a654aSHeejin Ahn if (MI.isTerminator()) {
1411f47a654aSHeejin Ahn for (auto &MO : MI.operands()) {
1412d8b3dc5aSHeejin Ahn if (MO.isMBB() && NewEndTryBBs.count(MO.getMBB())) {
1413d8b3dc5aSHeejin Ahn auto *BrDest = MO.getMBB();
1414d8b3dc5aSHeejin Ahn bool FoundEndBlock = false;
1415d8b3dc5aSHeejin Ahn for (; std::next(BrDest->getIterator()) != MF.end();
1416d8b3dc5aSHeejin Ahn BrDest = BrDest->getNextNode()) {
1417d8b3dc5aSHeejin Ahn for (const auto &MI : *BrDest) {
1418d8b3dc5aSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_BLOCK) {
1419d8b3dc5aSHeejin Ahn FoundEndBlock = true;
1420d8b3dc5aSHeejin Ahn break;
1421d8b3dc5aSHeejin Ahn }
1422d8b3dc5aSHeejin Ahn }
1423d8b3dc5aSHeejin Ahn if (FoundEndBlock)
1424d8b3dc5aSHeejin Ahn break;
1425d8b3dc5aSHeejin Ahn }
1426d8b3dc5aSHeejin Ahn assert(FoundEndBlock);
1427d8b3dc5aSHeejin Ahn MO.setMBB(BrDest);
1428f47a654aSHeejin Ahn }
1429f47a654aSHeejin Ahn }
1430f47a654aSHeejin Ahn }
1431f47a654aSHeejin Ahn }
14329f770b36SHeejin Ahn }
14339f770b36SHeejin Ahn
14349f770b36SHeejin Ahn return true;
1435c4ac74fbSHeejin Ahn }
1436c4ac74fbSHeejin Ahn
recalculateScopeTops(MachineFunction & MF)1437ed41945fSHeejin Ahn void WebAssemblyCFGStackify::recalculateScopeTops(MachineFunction &MF) {
1438ed41945fSHeejin Ahn // Renumber BBs and recalculate ScopeTop info because new BBs might have been
1439ed41945fSHeejin Ahn // created and inserted during fixing unwind mismatches.
1440ed41945fSHeejin Ahn MF.RenumberBlocks();
1441ed41945fSHeejin Ahn ScopeTops.clear();
1442ed41945fSHeejin Ahn ScopeTops.resize(MF.getNumBlockIDs());
1443ed41945fSHeejin Ahn for (auto &MBB : reverse(MF)) {
1444ed41945fSHeejin Ahn for (auto &MI : reverse(MBB)) {
1445ed41945fSHeejin Ahn if (ScopeTops[MBB.getNumber()])
1446ed41945fSHeejin Ahn break;
1447ed41945fSHeejin Ahn switch (MI.getOpcode()) {
1448ed41945fSHeejin Ahn case WebAssembly::END_BLOCK:
1449ed41945fSHeejin Ahn case WebAssembly::END_LOOP:
1450ed41945fSHeejin Ahn case WebAssembly::END_TRY:
1451ed41945fSHeejin Ahn case WebAssembly::DELEGATE:
1452ed41945fSHeejin Ahn updateScopeTops(EndToBegin[&MI]->getParent(), &MBB);
1453ed41945fSHeejin Ahn break;
1454ed41945fSHeejin Ahn case WebAssembly::CATCH:
1455ed41945fSHeejin Ahn case WebAssembly::CATCH_ALL:
1456ed41945fSHeejin Ahn updateScopeTops(EHPadToTry[&MBB]->getParent(), &MBB);
1457ed41945fSHeejin Ahn break;
1458ed41945fSHeejin Ahn }
1459ed41945fSHeejin Ahn }
1460ed41945fSHeejin Ahn }
1461ed41945fSHeejin Ahn }
1462ed41945fSHeejin Ahn
14632726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable,
14642726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar,
14652726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of
14662726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks
14672726b88cSDan Gohman /// that end at the function end need to have a return type signature that
14682726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function
14692726b88cSDan Gohman /// checks for such cases and fixes up the signatures.
fixEndsAtEndOfFunction(MachineFunction & MF)1470e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) {
1471e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
14722726b88cSDan Gohman
14732726b88cSDan Gohman if (MFI.getResults().empty())
14742726b88cSDan Gohman return;
14752726b88cSDan Gohman
14762cb27072SThomas Lively // MCInstLower will add the proper types to multivalue signatures based on the
14772cb27072SThomas Lively // function return type
14782cb27072SThomas Lively WebAssembly::BlockType RetType =
14792cb27072SThomas Lively MFI.getResults().size() > 1
14802cb27072SThomas Lively ? WebAssembly::BlockType::Multivalue
14812cb27072SThomas Lively : WebAssembly::BlockType(
14822cb27072SThomas Lively WebAssembly::toValType(MFI.getResults().front()));
14832726b88cSDan Gohman
1484d25c17f3SHeejin Ahn SmallVector<MachineBasicBlock::reverse_iterator, 4> Worklist;
1485d25c17f3SHeejin Ahn Worklist.push_back(MF.rbegin()->rbegin());
1486d25c17f3SHeejin Ahn
1487d25c17f3SHeejin Ahn auto Process = [&](MachineBasicBlock::reverse_iterator It) {
1488d25c17f3SHeejin Ahn auto *MBB = It->getParent();
1489d25c17f3SHeejin Ahn while (It != MBB->rend()) {
1490d25c17f3SHeejin Ahn MachineInstr &MI = *It++;
1491801bf7ebSShiva Chen if (MI.isPosition() || MI.isDebugInstr())
14922726b88cSDan Gohman continue;
14932cb27072SThomas Lively switch (MI.getOpcode()) {
1494d25c17f3SHeejin Ahn case WebAssembly::END_TRY: {
1495d25c17f3SHeejin Ahn // If a 'try''s return type is fixed, both its try body and catch body
1496d25c17f3SHeejin Ahn // should satisfy the return type, so we need to search 'end'
1497d25c17f3SHeejin Ahn // instructions before its corresponding 'catch' too.
1498d25c17f3SHeejin Ahn auto *EHPad = TryToEHPad.lookup(EndToBegin[&MI]);
1499d25c17f3SHeejin Ahn assert(EHPad);
15009f8b2576SHeejin Ahn auto NextIt =
15019f8b2576SHeejin Ahn std::next(WebAssembly::findCatch(EHPad)->getReverseIterator());
15029f8b2576SHeejin Ahn if (NextIt != EHPad->rend())
15039f8b2576SHeejin Ahn Worklist.push_back(NextIt);
1504d25c17f3SHeejin Ahn LLVM_FALLTHROUGH;
1505d25c17f3SHeejin Ahn }
15062cb27072SThomas Lively case WebAssembly::END_BLOCK:
15072cb27072SThomas Lively case WebAssembly::END_LOOP:
1508c390621aSHeejin Ahn case WebAssembly::DELEGATE:
150918c56a07SHeejin Ahn EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
15102726b88cSDan Gohman continue;
15112cb27072SThomas Lively default:
1512d25c17f3SHeejin Ahn // Something other than an `end`. We're done for this BB.
15132726b88cSDan Gohman return;
15142726b88cSDan Gohman }
15152726b88cSDan Gohman }
1516d25c17f3SHeejin Ahn // We've reached the beginning of a BB. Continue the search in the previous
1517d25c17f3SHeejin Ahn // BB.
1518d25c17f3SHeejin Ahn Worklist.push_back(MBB->getPrevNode()->rbegin());
1519d25c17f3SHeejin Ahn };
1520d25c17f3SHeejin Ahn
1521d25c17f3SHeejin Ahn while (!Worklist.empty())
1522d25c17f3SHeejin Ahn Process(Worklist.pop_back_val());
15232cb27072SThomas Lively }
15242726b88cSDan Gohman
1525d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body
1526d934cb88SDan Gohman // were a block.
appendEndToFunction(MachineFunction & MF,const WebAssemblyInstrInfo & TII)152718c56a07SHeejin Ahn static void appendEndToFunction(MachineFunction &MF,
1528d934cb88SDan Gohman const WebAssemblyInstrInfo &TII) {
152910b31358SDerek Schuff BuildMI(MF.back(), MF.back().end(),
153010b31358SDerek Schuff MF.back().findPrevDebugLoc(MF.back().end()),
1531d934cb88SDan Gohman TII.get(WebAssembly::END_FUNCTION));
1532d934cb88SDan Gohman }
1533d934cb88SDan Gohman
1534e76fa9ecSHeejin Ahn /// Insert LOOP/TRY/BLOCK markers at appropriate places.
placeMarkers(MachineFunction & MF)1535e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) {
1536e76fa9ecSHeejin Ahn // We allocate one more than the number of blocks in the function to
1537e76fa9ecSHeejin Ahn // accommodate for the possible fake block we may insert at the end.
1538e76fa9ecSHeejin Ahn ScopeTops.resize(MF.getNumBlockIDs() + 1);
15398fe7e86bSDan Gohman // Place the LOOP for MBB if MBB is the header of a loop.
1540e76fa9ecSHeejin Ahn for (auto &MBB : MF)
1541e76fa9ecSHeejin Ahn placeLoopMarker(MBB);
154244a5a4b1SHeejin Ahn
1543d6f48786SHeejin Ahn const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
154444a5a4b1SHeejin Ahn for (auto &MBB : MF) {
154544a5a4b1SHeejin Ahn if (MBB.isEHPad()) {
154644a5a4b1SHeejin Ahn // Place the TRY for MBB if MBB is the EH pad of an exception.
1547e76fa9ecSHeejin Ahn if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1548e76fa9ecSHeejin Ahn MF.getFunction().hasPersonalityFn())
1549e76fa9ecSHeejin Ahn placeTryMarker(MBB);
155044a5a4b1SHeejin Ahn } else {
155132807932SDan Gohman // Place the BLOCK for MBB if MBB is branched to from above.
1552e76fa9ecSHeejin Ahn placeBlockMarker(MBB);
1553950a13cfSDan Gohman }
155444a5a4b1SHeejin Ahn }
1555c4ac74fbSHeejin Ahn // Fix mismatches in unwind destinations induced by linearizing the code.
1556daeead4bSHeejin Ahn if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1557ed41945fSHeejin Ahn MF.getFunction().hasPersonalityFn()) {
1558ed41945fSHeejin Ahn bool Changed = fixCallUnwindMismatches(MF);
1559ed41945fSHeejin Ahn Changed |= fixCatchUnwindMismatches(MF);
1560ed41945fSHeejin Ahn if (Changed)
1561ed41945fSHeejin Ahn recalculateScopeTops(MF);
1562ed41945fSHeejin Ahn }
156344a5a4b1SHeejin Ahn }
1564950a13cfSDan Gohman
getBranchDepth(const SmallVectorImpl<EndMarkerInfo> & Stack,const MachineBasicBlock * MBB)15652968611fSHeejin Ahn unsigned WebAssemblyCFGStackify::getBranchDepth(
15662968611fSHeejin Ahn const SmallVectorImpl<EndMarkerInfo> &Stack, const MachineBasicBlock *MBB) {
15672968611fSHeejin Ahn unsigned Depth = 0;
15682968611fSHeejin Ahn for (auto X : reverse(Stack)) {
15692968611fSHeejin Ahn if (X.first == MBB)
15702968611fSHeejin Ahn break;
15712968611fSHeejin Ahn ++Depth;
15722968611fSHeejin Ahn }
15732968611fSHeejin Ahn assert(Depth < Stack.size() && "Branch destination should be in scope");
15742968611fSHeejin Ahn return Depth;
15752968611fSHeejin Ahn }
15762968611fSHeejin Ahn
getDelegateDepth(const SmallVectorImpl<EndMarkerInfo> & Stack,const MachineBasicBlock * MBB)15772968611fSHeejin Ahn unsigned WebAssemblyCFGStackify::getDelegateDepth(
15782968611fSHeejin Ahn const SmallVectorImpl<EndMarkerInfo> &Stack, const MachineBasicBlock *MBB) {
15792968611fSHeejin Ahn if (MBB == FakeCallerBB)
15802968611fSHeejin Ahn return Stack.size();
15812968611fSHeejin Ahn // Delegate's destination is either a catch or a another delegate BB. When the
15822968611fSHeejin Ahn // destination is another delegate, we can compute the argument in the same
15832968611fSHeejin Ahn // way as branches, because the target delegate BB only contains the single
15842968611fSHeejin Ahn // delegate instruction.
15852968611fSHeejin Ahn if (!MBB->isEHPad()) // Target is a delegate BB
15862968611fSHeejin Ahn return getBranchDepth(Stack, MBB);
15872968611fSHeejin Ahn
15882968611fSHeejin Ahn // When the delegate's destination is a catch BB, we need to use its
15892968611fSHeejin Ahn // corresponding try's end_try BB because Stack contains each marker's end BB.
15902968611fSHeejin Ahn // Also we need to check if the end marker instruction matches, because a
15912968611fSHeejin Ahn // single BB can contain multiple end markers, like this:
15922968611fSHeejin Ahn // bb:
15932968611fSHeejin Ahn // END_BLOCK
15942968611fSHeejin Ahn // END_TRY
15952968611fSHeejin Ahn // END_BLOCK
15962968611fSHeejin Ahn // END_TRY
15972968611fSHeejin Ahn // ...
15982968611fSHeejin Ahn //
15992968611fSHeejin Ahn // In case of branches getting the immediate that targets any of these is
16002968611fSHeejin Ahn // fine, but delegate has to exactly target the correct try.
16012968611fSHeejin Ahn unsigned Depth = 0;
16022968611fSHeejin Ahn const MachineInstr *EndTry = BeginToEnd[EHPadToTry[MBB]];
16032968611fSHeejin Ahn for (auto X : reverse(Stack)) {
16042968611fSHeejin Ahn if (X.first == EndTry->getParent() && X.second == EndTry)
16052968611fSHeejin Ahn break;
16062968611fSHeejin Ahn ++Depth;
16072968611fSHeejin Ahn }
16082968611fSHeejin Ahn assert(Depth < Stack.size() && "Delegate destination should be in scope");
16092968611fSHeejin Ahn return Depth;
16102968611fSHeejin Ahn }
16112968611fSHeejin Ahn
getRethrowDepth(const SmallVectorImpl<EndMarkerInfo> & Stack,const SmallVectorImpl<const MachineBasicBlock * > & EHPadStack)161235f5f797SHeejin Ahn unsigned WebAssemblyCFGStackify::getRethrowDepth(
161335f5f797SHeejin Ahn const SmallVectorImpl<EndMarkerInfo> &Stack,
161435f5f797SHeejin Ahn const SmallVectorImpl<const MachineBasicBlock *> &EHPadStack) {
161535f5f797SHeejin Ahn unsigned Depth = 0;
161635f5f797SHeejin Ahn // In our current implementation, rethrows always rethrow the exception caught
161735f5f797SHeejin Ahn // by the innermost enclosing catch. This means while traversing Stack in the
161835f5f797SHeejin Ahn // reverse direction, when we encounter END_TRY, we should check if the
161935f5f797SHeejin Ahn // END_TRY corresponds to the current innermost EH pad. For example:
162035f5f797SHeejin Ahn // try
162135f5f797SHeejin Ahn // ...
162235f5f797SHeejin Ahn // catch ;; (a)
162335f5f797SHeejin Ahn // try
162435f5f797SHeejin Ahn // rethrow 1 ;; (b)
162535f5f797SHeejin Ahn // catch ;; (c)
162635f5f797SHeejin Ahn // rethrow 0 ;; (d)
162735f5f797SHeejin Ahn // end ;; (e)
162835f5f797SHeejin Ahn // end ;; (f)
162935f5f797SHeejin Ahn //
163035f5f797SHeejin Ahn // When we are at 'rethrow' (d), while reversely traversing Stack the first
163135f5f797SHeejin Ahn // 'end' we encounter is the 'end' (e), which corresponds to the 'catch' (c).
163235f5f797SHeejin Ahn // And 'rethrow' (d) rethrows the exception caught by 'catch' (c), so we stop
163335f5f797SHeejin Ahn // there and the depth should be 0. But when we are at 'rethrow' (b), it
163435f5f797SHeejin Ahn // rethrows the exception caught by 'catch' (a), so when traversing Stack
163535f5f797SHeejin Ahn // reversely, we should skip the 'end' (e) and choose 'end' (f), which
163635f5f797SHeejin Ahn // corresponds to 'catch' (a).
163735f5f797SHeejin Ahn for (auto X : reverse(Stack)) {
163835f5f797SHeejin Ahn const MachineInstr *End = X.second;
163935f5f797SHeejin Ahn if (End->getOpcode() == WebAssembly::END_TRY) {
164035f5f797SHeejin Ahn auto *EHPad = TryToEHPad[EndToBegin[End]];
164135f5f797SHeejin Ahn if (EHPadStack.back() == EHPad)
164235f5f797SHeejin Ahn break;
164335f5f797SHeejin Ahn }
164435f5f797SHeejin Ahn ++Depth;
164535f5f797SHeejin Ahn }
164635f5f797SHeejin Ahn assert(Depth < Stack.size() && "Rethrow destination should be in scope");
164735f5f797SHeejin Ahn return Depth;
164835f5f797SHeejin Ahn }
164935f5f797SHeejin Ahn
rewriteDepthImmediates(MachineFunction & MF)1650e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) {
16511d68e80fSDan Gohman // Now rewrite references to basic blocks to be depth immediates.
16522968611fSHeejin Ahn SmallVector<EndMarkerInfo, 8> Stack;
165335f5f797SHeejin Ahn SmallVector<const MachineBasicBlock *, 8> EHPadStack;
16541d68e80fSDan Gohman for (auto &MBB : reverse(MF)) {
165514d656b3SKazu Hirata for (MachineInstr &MI : llvm::reverse(MBB)) {
16561d68e80fSDan Gohman switch (MI.getOpcode()) {
16571d68e80fSDan Gohman case WebAssembly::BLOCK:
1658e76fa9ecSHeejin Ahn case WebAssembly::TRY:
16592968611fSHeejin Ahn assert(ScopeTops[Stack.back().first->getNumber()]->getNumber() <=
1660e76fa9ecSHeejin Ahn MBB.getNumber() &&
1661e76fa9ecSHeejin Ahn "Block/try marker should be balanced");
1662e76fa9ecSHeejin Ahn Stack.pop_back();
1663e76fa9ecSHeejin Ahn break;
1664e76fa9ecSHeejin Ahn
16651d68e80fSDan Gohman case WebAssembly::LOOP:
16662968611fSHeejin Ahn assert(Stack.back().first == &MBB && "Loop top should be balanced");
16671d68e80fSDan Gohman Stack.pop_back();
16681d68e80fSDan Gohman break;
1669e76fa9ecSHeejin Ahn
16701d68e80fSDan Gohman case WebAssembly::END_BLOCK:
16712968611fSHeejin Ahn Stack.push_back(std::make_pair(&MBB, &MI));
1672ed41945fSHeejin Ahn break;
1673ed41945fSHeejin Ahn
167435f5f797SHeejin Ahn case WebAssembly::END_TRY: {
1675ed41945fSHeejin Ahn // We handle DELEGATE in the default level, because DELEGATE has
16762968611fSHeejin Ahn // immediate operands to rewrite.
16772968611fSHeejin Ahn Stack.push_back(std::make_pair(&MBB, &MI));
167835f5f797SHeejin Ahn auto *EHPad = TryToEHPad[EndToBegin[&MI]];
167935f5f797SHeejin Ahn EHPadStack.push_back(EHPad);
16801d68e80fSDan Gohman break;
168135f5f797SHeejin Ahn }
1682e76fa9ecSHeejin Ahn
16831d68e80fSDan Gohman case WebAssembly::END_LOOP:
16842968611fSHeejin Ahn Stack.push_back(std::make_pair(EndToBegin[&MI]->getParent(), &MI));
16851d68e80fSDan Gohman break;
1686e76fa9ecSHeejin Ahn
168735f5f797SHeejin Ahn case WebAssembly::CATCH:
168835f5f797SHeejin Ahn case WebAssembly::CATCH_ALL:
168935f5f797SHeejin Ahn EHPadStack.pop_back();
169035f5f797SHeejin Ahn break;
169135f5f797SHeejin Ahn
169235f5f797SHeejin Ahn case WebAssembly::RETHROW:
169335f5f797SHeejin Ahn MI.getOperand(0).setImm(getRethrowDepth(Stack, EHPadStack));
169435f5f797SHeejin Ahn break;
169535f5f797SHeejin Ahn
16961d68e80fSDan Gohman default:
16971d68e80fSDan Gohman if (MI.isTerminator()) {
16981d68e80fSDan Gohman // Rewrite MBB operands to be depth immediates.
16991d68e80fSDan Gohman SmallVector<MachineOperand, 4> Ops(MI.operands());
17001d68e80fSDan Gohman while (MI.getNumOperands() > 0)
170137b37838SShengchen Kan MI.removeOperand(MI.getNumOperands() - 1);
17021d68e80fSDan Gohman for (auto MO : Ops) {
1703ed41945fSHeejin Ahn if (MO.isMBB()) {
1704ed41945fSHeejin Ahn if (MI.getOpcode() == WebAssembly::DELEGATE)
1705ed41945fSHeejin Ahn MO = MachineOperand::CreateImm(
17062968611fSHeejin Ahn getDelegateDepth(Stack, MO.getMBB()));
1707ed41945fSHeejin Ahn else
17082968611fSHeejin Ahn MO = MachineOperand::CreateImm(
17092968611fSHeejin Ahn getBranchDepth(Stack, MO.getMBB()));
1710ed41945fSHeejin Ahn }
17111d68e80fSDan Gohman MI.addOperand(MF, MO);
171232807932SDan Gohman }
17131d68e80fSDan Gohman }
1714ed41945fSHeejin Ahn
17152968611fSHeejin Ahn if (MI.getOpcode() == WebAssembly::DELEGATE)
17162968611fSHeejin Ahn Stack.push_back(std::make_pair(&MBB, &MI));
17171d68e80fSDan Gohman break;
17181d68e80fSDan Gohman }
17191d68e80fSDan Gohman }
17201d68e80fSDan Gohman }
17211d68e80fSDan Gohman assert(Stack.empty() && "Control flow should be balanced");
1722e76fa9ecSHeejin Ahn }
17232726b88cSDan Gohman
cleanupFunctionData(MachineFunction & MF)1724ed41945fSHeejin Ahn void WebAssemblyCFGStackify::cleanupFunctionData(MachineFunction &MF) {
1725ed41945fSHeejin Ahn if (FakeCallerBB)
172691a0da01SMircea Trofin MF.deleteMachineBasicBlock(FakeCallerBB);
1727ed41945fSHeejin Ahn AppendixBB = FakeCallerBB = nullptr;
1728ed41945fSHeejin Ahn }
1729ed41945fSHeejin Ahn
releaseMemory()1730e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::releaseMemory() {
1731e76fa9ecSHeejin Ahn ScopeTops.clear();
1732e76fa9ecSHeejin Ahn BeginToEnd.clear();
1733e76fa9ecSHeejin Ahn EndToBegin.clear();
1734e76fa9ecSHeejin Ahn TryToEHPad.clear();
1735e76fa9ecSHeejin Ahn EHPadToTry.clear();
17361d68e80fSDan Gohman }
173732807932SDan Gohman
runOnMachineFunction(MachineFunction & MF)1738950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
1739d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n"
1740950a13cfSDan Gohman "********** Function: "
1741950a13cfSDan Gohman << MF.getName() << '\n');
1742cf699b45SHeejin Ahn const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
1743950a13cfSDan Gohman
1744e76fa9ecSHeejin Ahn releaseMemory();
1745e76fa9ecSHeejin Ahn
1746e040533eSDan Gohman // Liveness is not tracked for VALUE_STACK physreg.
17479c3bf318SDerek Schuff MF.getRegInfo().invalidateLiveness();
1748950a13cfSDan Gohman
1749e76fa9ecSHeejin Ahn // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes.
1750e76fa9ecSHeejin Ahn placeMarkers(MF);
1751e76fa9ecSHeejin Ahn
1752c4ac74fbSHeejin Ahn // Remove unnecessary instructions possibly introduced by try/end_trys.
1753cf699b45SHeejin Ahn if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1754cf699b45SHeejin Ahn MF.getFunction().hasPersonalityFn())
1755cf699b45SHeejin Ahn removeUnnecessaryInstrs(MF);
1756cf699b45SHeejin Ahn
1757e76fa9ecSHeejin Ahn // Convert MBB operands in terminators to relative depth immediates.
1758e76fa9ecSHeejin Ahn rewriteDepthImmediates(MF);
1759e76fa9ecSHeejin Ahn
1760e76fa9ecSHeejin Ahn // Fix up block/loop/try signatures at the end of the function to conform to
1761e76fa9ecSHeejin Ahn // WebAssembly's rules.
1762e76fa9ecSHeejin Ahn fixEndsAtEndOfFunction(MF);
1763e76fa9ecSHeejin Ahn
1764e76fa9ecSHeejin Ahn // Add an end instruction at the end of the function body.
1765e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1766e76fa9ecSHeejin Ahn if (!MF.getSubtarget<WebAssemblySubtarget>()
1767e76fa9ecSHeejin Ahn .getTargetTriple()
1768e76fa9ecSHeejin Ahn .isOSBinFormatELF())
176918c56a07SHeejin Ahn appendEndToFunction(MF, TII);
177032807932SDan Gohman
1771ed41945fSHeejin Ahn cleanupFunctionData(MF);
1772ed41945fSHeejin Ahn
17731aaa481fSHeejin Ahn MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified();
1774950a13cfSDan Gohman return true;
1775950a13cfSDan Gohman }
1776