1950a13cfSDan Gohman //===-- WebAssemblyCFGStackify.cpp - CFG Stackification -------------------===//
2950a13cfSDan Gohman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6950a13cfSDan Gohman //
7950a13cfSDan Gohman //===----------------------------------------------------------------------===//
8950a13cfSDan Gohman ///
9950a13cfSDan Gohman /// \file
105f8f34e4SAdrian Prantl /// This file implements a CFG stacking pass.
11950a13cfSDan Gohman ///
12e76fa9ecSHeejin Ahn /// This pass inserts BLOCK, LOOP, and TRY markers to mark the start of scopes,
13e76fa9ecSHeejin Ahn /// since scope boundaries serve as the labels for WebAssembly's control
14e76fa9ecSHeejin Ahn /// transfers.
15950a13cfSDan Gohman ///
16950a13cfSDan Gohman /// This is sufficient to convert arbitrary CFGs into a form that works on
17950a13cfSDan Gohman /// WebAssembly, provided that all loops are single-entry.
18950a13cfSDan Gohman ///
19e76fa9ecSHeejin Ahn /// In case we use exceptions, this pass also fixes mismatches in unwind
20e76fa9ecSHeejin Ahn /// destinations created during transforming CFG into wasm structured format.
21e76fa9ecSHeejin Ahn ///
22950a13cfSDan Gohman //===----------------------------------------------------------------------===//
23950a13cfSDan Gohman 
246bda14b3SChandler Carruth #include "WebAssembly.h"
25e76fa9ecSHeejin Ahn #include "WebAssemblyExceptionInfo.h"
26ed0f1138SDan Gohman #include "WebAssemblyMachineFunctionInfo.h"
27950a13cfSDan Gohman #include "WebAssemblySubtarget.h"
284fc4e42dSDan Gohman #include "WebAssemblyUtilities.h"
29*c4ac74fbSHeejin Ahn #include "llvm/ADT/Statistic.h"
3032807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h"
31950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
32e76fa9ecSHeejin Ahn #include "llvm/MC/MCAsmInfo.h"
33950a13cfSDan Gohman using namespace llvm;
34950a13cfSDan Gohman 
35950a13cfSDan Gohman #define DEBUG_TYPE "wasm-cfg-stackify"
36950a13cfSDan Gohman 
37*c4ac74fbSHeejin Ahn STATISTIC(NumUnwindMismatches, "Number of EH pad unwind mismatches found");
38*c4ac74fbSHeejin Ahn 
39950a13cfSDan Gohman namespace {
40950a13cfSDan Gohman class WebAssemblyCFGStackify final : public MachineFunctionPass {
41117296c0SMehdi Amini   StringRef getPassName() const override { return "WebAssembly CFG Stackify"; }
42950a13cfSDan Gohman 
43950a13cfSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
4432807932SDan Gohman     AU.addRequired<MachineDominatorTree>();
45950a13cfSDan Gohman     AU.addRequired<MachineLoopInfo>();
46e76fa9ecSHeejin Ahn     AU.addRequired<WebAssemblyExceptionInfo>();
47950a13cfSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
48950a13cfSDan Gohman   }
49950a13cfSDan Gohman 
50950a13cfSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
51950a13cfSDan Gohman 
52e76fa9ecSHeejin Ahn   // For each block whose label represents the end of a scope, record the block
53e76fa9ecSHeejin Ahn   // which holds the beginning of the scope. This will allow us to quickly skip
54e76fa9ecSHeejin Ahn   // over scoped regions when walking blocks.
55e76fa9ecSHeejin Ahn   SmallVector<MachineBasicBlock *, 8> ScopeTops;
56e76fa9ecSHeejin Ahn 
57*c4ac74fbSHeejin Ahn   // Placing markers.
58e76fa9ecSHeejin Ahn   void placeMarkers(MachineFunction &MF);
59e76fa9ecSHeejin Ahn   void placeBlockMarker(MachineBasicBlock &MBB);
60e76fa9ecSHeejin Ahn   void placeLoopMarker(MachineBasicBlock &MBB);
61e76fa9ecSHeejin Ahn   void placeTryMarker(MachineBasicBlock &MBB);
62cf699b45SHeejin Ahn   void removeUnnecessaryInstrs(MachineFunction &MF);
63*c4ac74fbSHeejin Ahn   bool fixUnwindMismatches(MachineFunction &MF);
64e76fa9ecSHeejin Ahn   void rewriteDepthImmediates(MachineFunction &MF);
65e76fa9ecSHeejin Ahn   void fixEndsAtEndOfFunction(MachineFunction &MF);
66e76fa9ecSHeejin Ahn 
67e76fa9ecSHeejin Ahn   // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY).
68e76fa9ecSHeejin Ahn   DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd;
69e76fa9ecSHeejin Ahn   // For each END_(BLOCK|LOOP|TRY), the corresponding BLOCK|LOOP|TRY.
70e76fa9ecSHeejin Ahn   DenseMap<const MachineInstr *, MachineInstr *> EndToBegin;
71e76fa9ecSHeejin Ahn   // <TRY marker, EH pad> map
72e76fa9ecSHeejin Ahn   DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad;
73e76fa9ecSHeejin Ahn   // <EH pad, TRY marker> map
74e76fa9ecSHeejin Ahn   DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry;
75e76fa9ecSHeejin Ahn 
76*c4ac74fbSHeejin Ahn   // There can be an appendix block at the end of each function, shared for:
77*c4ac74fbSHeejin Ahn   // - creating a correct signature for fallthrough returns
78*c4ac74fbSHeejin Ahn   // - target for rethrows that need to unwind to the caller, but are trapped
79*c4ac74fbSHeejin Ahn   //   inside another try/catch
80*c4ac74fbSHeejin Ahn   MachineBasicBlock *AppendixBB = nullptr;
81*c4ac74fbSHeejin Ahn   MachineBasicBlock *getAppendixBlock(MachineFunction &MF) {
82*c4ac74fbSHeejin Ahn     if (!AppendixBB) {
83*c4ac74fbSHeejin Ahn       AppendixBB = MF.CreateMachineBasicBlock();
84*c4ac74fbSHeejin Ahn       // Give it a fake predecessor so that AsmPrinter prints its label.
85*c4ac74fbSHeejin Ahn       AppendixBB->addSuccessor(AppendixBB);
86*c4ac74fbSHeejin Ahn       MF.push_back(AppendixBB);
87*c4ac74fbSHeejin Ahn     }
88*c4ac74fbSHeejin Ahn     return AppendixBB;
89*c4ac74fbSHeejin Ahn   }
90*c4ac74fbSHeejin Ahn 
91cf699b45SHeejin Ahn   // Helper functions to register / unregister scope information created by
92cf699b45SHeejin Ahn   // marker instructions.
93e76fa9ecSHeejin Ahn   void registerScope(MachineInstr *Begin, MachineInstr *End);
94e76fa9ecSHeejin Ahn   void registerTryScope(MachineInstr *Begin, MachineInstr *End,
95e76fa9ecSHeejin Ahn                         MachineBasicBlock *EHPad);
96cf699b45SHeejin Ahn   void unregisterScope(MachineInstr *Begin);
97e76fa9ecSHeejin Ahn 
98950a13cfSDan Gohman public:
99950a13cfSDan Gohman   static char ID; // Pass identification, replacement for typeid
100950a13cfSDan Gohman   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
101e76fa9ecSHeejin Ahn   ~WebAssemblyCFGStackify() override { releaseMemory(); }
102e76fa9ecSHeejin Ahn   void releaseMemory() override;
103950a13cfSDan Gohman };
104950a13cfSDan Gohman } // end anonymous namespace
105950a13cfSDan Gohman 
106950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0;
10740926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE,
108*c4ac74fbSHeejin Ahn                 "Insert BLOCK/LOOP/TRY markers for WebAssembly scopes", false,
109f208f631SHeejin Ahn                 false)
11040926451SJacob Gravelle 
111950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() {
112950a13cfSDan Gohman   return new WebAssemblyCFGStackify();
113950a13cfSDan Gohman }
114950a13cfSDan Gohman 
115b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as
116b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized
117b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough
118b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any
119b3aa1ecaSDan Gohman /// explicit mentions.
12018c56a07SHeejin Ahn static bool explicitlyBranchesTo(MachineBasicBlock *Pred,
12135e4a289SDan Gohman                                  MachineBasicBlock *MBB) {
122b3aa1ecaSDan Gohman   for (MachineInstr &MI : Pred->terminators())
123b3aa1ecaSDan Gohman     for (MachineOperand &MO : MI.explicit_operands())
124b3aa1ecaSDan Gohman       if (MO.isMBB() && MO.getMBB() == MBB)
125b3aa1ecaSDan Gohman         return true;
126b3aa1ecaSDan Gohman   return false;
127b3aa1ecaSDan Gohman }
128b3aa1ecaSDan Gohman 
129e76fa9ecSHeejin Ahn // Returns an iterator to the earliest position possible within the MBB,
130e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
131e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains
132e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, AfterSet is only
133e76fa9ecSHeejin Ahn // used for sanity checking.
134e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator
13518c56a07SHeejin Ahn getEarliestInsertPos(MachineBasicBlock *MBB,
136e76fa9ecSHeejin Ahn                      const SmallPtrSet<const MachineInstr *, 4> &BeforeSet,
137e76fa9ecSHeejin Ahn                      const SmallPtrSet<const MachineInstr *, 4> &AfterSet) {
138e76fa9ecSHeejin Ahn   auto InsertPos = MBB->end();
139e76fa9ecSHeejin Ahn   while (InsertPos != MBB->begin()) {
140e76fa9ecSHeejin Ahn     if (BeforeSet.count(&*std::prev(InsertPos))) {
141e76fa9ecSHeejin Ahn #ifndef NDEBUG
142e76fa9ecSHeejin Ahn       // Sanity check
143e76fa9ecSHeejin Ahn       for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos)
144e76fa9ecSHeejin Ahn         assert(!AfterSet.count(&*std::prev(Pos)));
145e76fa9ecSHeejin Ahn #endif
146e76fa9ecSHeejin Ahn       break;
147e76fa9ecSHeejin Ahn     }
148e76fa9ecSHeejin Ahn     --InsertPos;
149e76fa9ecSHeejin Ahn   }
150e76fa9ecSHeejin Ahn   return InsertPos;
151e76fa9ecSHeejin Ahn }
152e76fa9ecSHeejin Ahn 
153e76fa9ecSHeejin Ahn // Returns an iterator to the latest position possible within the MBB,
154e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
155e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains
156e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, BeforeSet is only
157e76fa9ecSHeejin Ahn // used for sanity checking.
158e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator
15918c56a07SHeejin Ahn getLatestInsertPos(MachineBasicBlock *MBB,
160e76fa9ecSHeejin Ahn                    const SmallPtrSet<const MachineInstr *, 4> &BeforeSet,
161e76fa9ecSHeejin Ahn                    const SmallPtrSet<const MachineInstr *, 4> &AfterSet) {
162e76fa9ecSHeejin Ahn   auto InsertPos = MBB->begin();
163e76fa9ecSHeejin Ahn   while (InsertPos != MBB->end()) {
164e76fa9ecSHeejin Ahn     if (AfterSet.count(&*InsertPos)) {
165e76fa9ecSHeejin Ahn #ifndef NDEBUG
166e76fa9ecSHeejin Ahn       // Sanity check
167e76fa9ecSHeejin Ahn       for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos)
168e76fa9ecSHeejin Ahn         assert(!BeforeSet.count(&*Pos));
169e76fa9ecSHeejin Ahn #endif
170e76fa9ecSHeejin Ahn       break;
171e76fa9ecSHeejin Ahn     }
172e76fa9ecSHeejin Ahn     ++InsertPos;
173e76fa9ecSHeejin Ahn   }
174e76fa9ecSHeejin Ahn   return InsertPos;
175e76fa9ecSHeejin Ahn }
176e76fa9ecSHeejin Ahn 
177e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin,
178e76fa9ecSHeejin Ahn                                            MachineInstr *End) {
179e76fa9ecSHeejin Ahn   BeginToEnd[Begin] = End;
180e76fa9ecSHeejin Ahn   EndToBegin[End] = Begin;
181e76fa9ecSHeejin Ahn }
182e76fa9ecSHeejin Ahn 
183e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin,
184e76fa9ecSHeejin Ahn                                               MachineInstr *End,
185e76fa9ecSHeejin Ahn                                               MachineBasicBlock *EHPad) {
186e76fa9ecSHeejin Ahn   registerScope(Begin, End);
187e76fa9ecSHeejin Ahn   TryToEHPad[Begin] = EHPad;
188e76fa9ecSHeejin Ahn   EHPadToTry[EHPad] = Begin;
189e76fa9ecSHeejin Ahn }
190e76fa9ecSHeejin Ahn 
191cf699b45SHeejin Ahn void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) {
192cf699b45SHeejin Ahn   assert(BeginToEnd.count(Begin));
193cf699b45SHeejin Ahn   MachineInstr *End = BeginToEnd[Begin];
194cf699b45SHeejin Ahn   assert(EndToBegin.count(End));
195cf699b45SHeejin Ahn   BeginToEnd.erase(Begin);
196cf699b45SHeejin Ahn   EndToBegin.erase(End);
197cf699b45SHeejin Ahn   MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin);
198cf699b45SHeejin Ahn   if (EHPad) {
199cf699b45SHeejin Ahn     assert(EHPadToTry.count(EHPad));
200cf699b45SHeejin Ahn     TryToEHPad.erase(Begin);
201cf699b45SHeejin Ahn     EHPadToTry.erase(EHPad);
202cf699b45SHeejin Ahn   }
203cf699b45SHeejin Ahn }
204cf699b45SHeejin Ahn 
20532807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed).
206*c4ac74fbSHeejin Ahn // TODO Consider a more generalized way of handling block (and also loop and
207*c4ac74fbSHeejin Ahn // try) signatures when we implement the multi-value proposal later.
208e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) {
20944a5a4b1SHeejin Ahn   assert(!MBB.isEHPad());
210e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
211e76fa9ecSHeejin Ahn   auto &MDT = getAnalysis<MachineDominatorTree>();
212e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
213e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
214e76fa9ecSHeejin Ahn 
2158fe7e86bSDan Gohman   // First compute the nearest common dominator of all forward non-fallthrough
2168fe7e86bSDan Gohman   // predecessors so that we minimize the time that the BLOCK is on the stack,
2178fe7e86bSDan Gohman   // which reduces overall stack height.
21832807932SDan Gohman   MachineBasicBlock *Header = nullptr;
21932807932SDan Gohman   bool IsBranchedTo = false;
220d6f48786SHeejin Ahn   bool IsBrOnExn = false;
221d6f48786SHeejin Ahn   MachineInstr *BrOnExn = nullptr;
22232807932SDan Gohman   int MBBNumber = MBB.getNumber();
223e76fa9ecSHeejin Ahn   for (MachineBasicBlock *Pred : MBB.predecessors()) {
22432807932SDan Gohman     if (Pred->getNumber() < MBBNumber) {
22532807932SDan Gohman       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
22618c56a07SHeejin Ahn       if (explicitlyBranchesTo(Pred, &MBB)) {
22732807932SDan Gohman         IsBranchedTo = true;
228d6f48786SHeejin Ahn         if (Pred->getFirstTerminator()->getOpcode() == WebAssembly::BR_ON_EXN) {
229d6f48786SHeejin Ahn           IsBrOnExn = true;
230d6f48786SHeejin Ahn           assert(!BrOnExn && "There should be only one br_on_exn per block");
231d6f48786SHeejin Ahn           BrOnExn = &*Pred->getFirstTerminator();
232d6f48786SHeejin Ahn         }
233d6f48786SHeejin Ahn       }
23432807932SDan Gohman     }
235e76fa9ecSHeejin Ahn   }
23632807932SDan Gohman   if (!Header)
23732807932SDan Gohman     return;
23832807932SDan Gohman   if (!IsBranchedTo)
23932807932SDan Gohman     return;
24032807932SDan Gohman 
2418fe7e86bSDan Gohman   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
2425c644c9bSHeejin Ahn   MachineBasicBlock *LayoutPred = MBB.getPrevNode();
2438fe7e86bSDan Gohman 
2448fe7e86bSDan Gohman   // If the nearest common dominator is inside a more deeply nested context,
2458fe7e86bSDan Gohman   // walk out to the nearest scope which isn't more deeply nested.
2468fe7e86bSDan Gohman   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
2478fe7e86bSDan Gohman     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
2488fe7e86bSDan Gohman       if (ScopeTop->getNumber() > Header->getNumber()) {
2498fe7e86bSDan Gohman         // Skip over an intervening scope.
2505c644c9bSHeejin Ahn         I = std::next(ScopeTop->getIterator());
2518fe7e86bSDan Gohman       } else {
2528fe7e86bSDan Gohman         // We found a scope level at an appropriate depth.
2538fe7e86bSDan Gohman         Header = ScopeTop;
2548fe7e86bSDan Gohman         break;
2558fe7e86bSDan Gohman       }
2568fe7e86bSDan Gohman     }
2578fe7e86bSDan Gohman   }
2588fe7e86bSDan Gohman 
2598fe7e86bSDan Gohman   // Decide where in Header to put the BLOCK.
260e76fa9ecSHeejin Ahn 
261e76fa9ecSHeejin Ahn   // Instructions that should go before the BLOCK.
262e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
263e76fa9ecSHeejin Ahn   // Instructions that should go after the BLOCK.
264e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
265e76fa9ecSHeejin Ahn   for (const auto &MI : *Header) {
26644a5a4b1SHeejin Ahn     // If there is a previously placed LOOP marker and the bottom block of the
26744a5a4b1SHeejin Ahn     // loop is above MBB, it should be after the BLOCK, because the loop is
26844a5a4b1SHeejin Ahn     // nested in this BLOCK. Otherwise it should be before the BLOCK.
26944a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP) {
27044a5a4b1SHeejin Ahn       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
27144a5a4b1SHeejin Ahn       if (MBB.getNumber() > LoopBottom->getNumber())
272e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
273e76fa9ecSHeejin Ahn #ifndef NDEBUG
274e76fa9ecSHeejin Ahn       else
275e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
276e76fa9ecSHeejin Ahn #endif
277e76fa9ecSHeejin Ahn     }
278e76fa9ecSHeejin Ahn 
27944a5a4b1SHeejin Ahn     // All previously inserted BLOCK/TRY markers should be after the BLOCK
28044a5a4b1SHeejin Ahn     // because they are all nested blocks.
28144a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::BLOCK ||
28244a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::TRY)
283e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
284e76fa9ecSHeejin Ahn 
285e76fa9ecSHeejin Ahn #ifndef NDEBUG
286e76fa9ecSHeejin Ahn     // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK.
287e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
288e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_LOOP ||
289e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY)
290e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
291e76fa9ecSHeejin Ahn #endif
292e76fa9ecSHeejin Ahn 
293e76fa9ecSHeejin Ahn     // Terminators should go after the BLOCK.
294e76fa9ecSHeejin Ahn     if (MI.isTerminator())
295e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
296e76fa9ecSHeejin Ahn   }
297e76fa9ecSHeejin Ahn 
298e76fa9ecSHeejin Ahn   // Local expression tree should go after the BLOCK.
299e76fa9ecSHeejin Ahn   for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
300e76fa9ecSHeejin Ahn        --I) {
301409b4391SYury Delendik     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
302409b4391SYury Delendik       continue;
303e76fa9ecSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
304e76fa9ecSHeejin Ahn       AfterSet.insert(&*std::prev(I));
305e76fa9ecSHeejin Ahn     else
306e76fa9ecSHeejin Ahn       break;
30732807932SDan Gohman   }
30832807932SDan Gohman 
3098fe7e86bSDan Gohman   // Add the BLOCK.
310d6f48786SHeejin Ahn 
311d6f48786SHeejin Ahn   // 'br_on_exn' extracts except_ref object and pushes variable number of values
312d6f48786SHeejin Ahn   // depending on its tag. For C++ exception, its a single i32 value, and the
313d6f48786SHeejin Ahn   // generated code will be in the form of:
314d6f48786SHeejin Ahn   // block i32
315d6f48786SHeejin Ahn   //   br_on_exn 0, $__cpp_exception
316d6f48786SHeejin Ahn   //   rethrow
317d6f48786SHeejin Ahn   // end_block
318d6f48786SHeejin Ahn   WebAssembly::ExprType ReturnType = WebAssembly::ExprType::Void;
319d6f48786SHeejin Ahn   if (IsBrOnExn) {
320d6f48786SHeejin Ahn     const char *TagName = BrOnExn->getOperand(1).getSymbolName();
321d6f48786SHeejin Ahn     if (std::strcmp(TagName, "__cpp_exception") != 0)
322d6f48786SHeejin Ahn       llvm_unreachable("Only C++ exception is supported");
323d6f48786SHeejin Ahn     ReturnType = WebAssembly::ExprType::I32;
324d6f48786SHeejin Ahn   }
325d6f48786SHeejin Ahn 
32618c56a07SHeejin Ahn   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
32792401cc1SHeejin Ahn   MachineInstr *Begin =
32892401cc1SHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
3292726b88cSDan Gohman               TII.get(WebAssembly::BLOCK))
330d6f48786SHeejin Ahn           .addImm(int64_t(ReturnType));
3311d68e80fSDan Gohman 
332e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_BLOCK.
333e76fa9ecSHeejin Ahn   BeforeSet.clear();
334e76fa9ecSHeejin Ahn   AfterSet.clear();
335e76fa9ecSHeejin Ahn   for (auto &MI : MBB) {
336e76fa9ecSHeejin Ahn #ifndef NDEBUG
337e76fa9ecSHeejin Ahn     // END_BLOCK should precede existing LOOP and TRY markers.
338e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP ||
339e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::TRY)
340e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
341e76fa9ecSHeejin Ahn #endif
342e76fa9ecSHeejin Ahn 
343e76fa9ecSHeejin Ahn     // If there is a previously placed END_LOOP marker and the header of the
344e76fa9ecSHeejin Ahn     // loop is above this block's header, the END_LOOP should be placed after
345e76fa9ecSHeejin Ahn     // the BLOCK, because the loop contains this block. Otherwise the END_LOOP
346e76fa9ecSHeejin Ahn     // should be placed before the BLOCK. The same for END_TRY.
347e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP ||
348e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY) {
349e76fa9ecSHeejin Ahn       if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
350e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
351e76fa9ecSHeejin Ahn #ifndef NDEBUG
352e76fa9ecSHeejin Ahn       else
353e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
354e76fa9ecSHeejin Ahn #endif
355e76fa9ecSHeejin Ahn     }
356e76fa9ecSHeejin Ahn   }
357e76fa9ecSHeejin Ahn 
3581d68e80fSDan Gohman   // Mark the end of the block.
35918c56a07SHeejin Ahn   InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
36010b31358SDerek Schuff   MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
3612726b88cSDan Gohman                               TII.get(WebAssembly::END_BLOCK));
362e76fa9ecSHeejin Ahn   registerScope(Begin, End);
3638fe7e86bSDan Gohman 
3648fe7e86bSDan Gohman   // Track the farthest-spanning scope that ends at this point.
3658fe7e86bSDan Gohman   int Number = MBB.getNumber();
3668fe7e86bSDan Gohman   if (!ScopeTops[Number] ||
3678fe7e86bSDan Gohman       ScopeTops[Number]->getNumber() > Header->getNumber())
3688fe7e86bSDan Gohman     ScopeTops[Number] = Header;
369950a13cfSDan Gohman }
370950a13cfSDan Gohman 
3718fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
372e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) {
373e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
374e76fa9ecSHeejin Ahn   const auto &MLI = getAnalysis<MachineLoopInfo>();
375e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
376e76fa9ecSHeejin Ahn 
3778fe7e86bSDan Gohman   MachineLoop *Loop = MLI.getLoopFor(&MBB);
3788fe7e86bSDan Gohman   if (!Loop || Loop->getHeader() != &MBB)
3798fe7e86bSDan Gohman     return;
3808fe7e86bSDan Gohman 
3818fe7e86bSDan Gohman   // The operand of a LOOP is the first block after the loop. If the loop is the
3828fe7e86bSDan Gohman   // bottom of the function, insert a dummy block at the end.
383817811caSHeejin Ahn   MachineBasicBlock *Bottom = WebAssembly::getBottom(Loop);
3845c644c9bSHeejin Ahn   auto Iter = std::next(Bottom->getIterator());
385e3e4a5ffSDan Gohman   if (Iter == MF.end()) {
386*c4ac74fbSHeejin Ahn     getAppendixBlock(MF);
3875c644c9bSHeejin Ahn     Iter = std::next(Bottom->getIterator());
388e3e4a5ffSDan Gohman   }
3898fe7e86bSDan Gohman   MachineBasicBlock *AfterLoop = &*Iter;
390f6857223SDan Gohman 
391e76fa9ecSHeejin Ahn   // Decide where in Header to put the LOOP.
392e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
393e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
394e76fa9ecSHeejin Ahn   for (const auto &MI : MBB) {
395e76fa9ecSHeejin Ahn     // LOOP marker should be after any existing loop that ends here. Otherwise
396e76fa9ecSHeejin Ahn     // we assume the instruction belongs to the loop.
397e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP)
398e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
399e76fa9ecSHeejin Ahn #ifndef NDEBUG
400e76fa9ecSHeejin Ahn     else
401e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
402e76fa9ecSHeejin Ahn #endif
403e76fa9ecSHeejin Ahn   }
404e76fa9ecSHeejin Ahn 
405e76fa9ecSHeejin Ahn   // Mark the beginning of the loop.
40618c56a07SHeejin Ahn   auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
40710b31358SDerek Schuff   MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos),
4082726b88cSDan Gohman                                 TII.get(WebAssembly::LOOP))
4094fc4e42dSDan Gohman                             .addImm(int64_t(WebAssembly::ExprType::Void));
4101d68e80fSDan Gohman 
411e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_LOOP.
412e76fa9ecSHeejin Ahn   BeforeSet.clear();
413e76fa9ecSHeejin Ahn   AfterSet.clear();
414e76fa9ecSHeejin Ahn #ifndef NDEBUG
415e76fa9ecSHeejin Ahn   for (const auto &MI : MBB)
416e76fa9ecSHeejin Ahn     // Existing END_LOOP markers belong to parent loops of this loop
417e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP)
418e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
419e76fa9ecSHeejin Ahn #endif
420e76fa9ecSHeejin Ahn 
421e76fa9ecSHeejin Ahn   // Mark the end of the loop (using arbitrary debug location that branched to
422e76fa9ecSHeejin Ahn   // the loop end as its location).
42318c56a07SHeejin Ahn   InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet);
42467f74aceSHeejin Ahn   DebugLoc EndDL = AfterLoop->pred_empty()
42567f74aceSHeejin Ahn                        ? DebugLoc()
42667f74aceSHeejin Ahn                        : (*AfterLoop->pred_rbegin())->findBranchDebugLoc();
427e76fa9ecSHeejin Ahn   MachineInstr *End =
428e76fa9ecSHeejin Ahn       BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP));
429e76fa9ecSHeejin Ahn   registerScope(Begin, End);
4308fe7e86bSDan Gohman 
4318fe7e86bSDan Gohman   assert((!ScopeTops[AfterLoop->getNumber()] ||
4328fe7e86bSDan Gohman           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
433442bfcecSDan Gohman          "With block sorting the outermost loop for a block should be first.");
4348fe7e86bSDan Gohman   if (!ScopeTops[AfterLoop->getNumber()])
4358fe7e86bSDan Gohman     ScopeTops[AfterLoop->getNumber()] = &MBB;
436e3e4a5ffSDan Gohman }
437950a13cfSDan Gohman 
438e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) {
43944a5a4b1SHeejin Ahn   assert(MBB.isEHPad());
440e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
441e76fa9ecSHeejin Ahn   auto &MDT = getAnalysis<MachineDominatorTree>();
442e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
443e76fa9ecSHeejin Ahn   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
444e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
445e76fa9ecSHeejin Ahn 
446e76fa9ecSHeejin Ahn   // Compute the nearest common dominator of all unwind predecessors
447e76fa9ecSHeejin Ahn   MachineBasicBlock *Header = nullptr;
448e76fa9ecSHeejin Ahn   int MBBNumber = MBB.getNumber();
449e76fa9ecSHeejin Ahn   for (auto *Pred : MBB.predecessors()) {
450e76fa9ecSHeejin Ahn     if (Pred->getNumber() < MBBNumber) {
451e76fa9ecSHeejin Ahn       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
45218c56a07SHeejin Ahn       assert(!explicitlyBranchesTo(Pred, &MBB) &&
453e76fa9ecSHeejin Ahn              "Explicit branch to an EH pad!");
454e76fa9ecSHeejin Ahn     }
455e76fa9ecSHeejin Ahn   }
456e76fa9ecSHeejin Ahn   if (!Header)
457e76fa9ecSHeejin Ahn     return;
458e76fa9ecSHeejin Ahn 
459e76fa9ecSHeejin Ahn   // If this try is at the bottom of the function, insert a dummy block at the
460e76fa9ecSHeejin Ahn   // end.
461e76fa9ecSHeejin Ahn   WebAssemblyException *WE = WEI.getExceptionFor(&MBB);
462e76fa9ecSHeejin Ahn   assert(WE);
463e76fa9ecSHeejin Ahn   MachineBasicBlock *Bottom = WebAssembly::getBottom(WE);
464e76fa9ecSHeejin Ahn 
4655c644c9bSHeejin Ahn   auto Iter = std::next(Bottom->getIterator());
466e76fa9ecSHeejin Ahn   if (Iter == MF.end()) {
467*c4ac74fbSHeejin Ahn     getAppendixBlock(MF);
4685c644c9bSHeejin Ahn     Iter = std::next(Bottom->getIterator());
469e76fa9ecSHeejin Ahn   }
47020cf0749SHeejin Ahn   MachineBasicBlock *Cont = &*Iter;
471e76fa9ecSHeejin Ahn 
47220cf0749SHeejin Ahn   assert(Cont != &MF.front());
4735c644c9bSHeejin Ahn   MachineBasicBlock *LayoutPred = Cont->getPrevNode();
474e76fa9ecSHeejin Ahn 
475e76fa9ecSHeejin Ahn   // If the nearest common dominator is inside a more deeply nested context,
476e76fa9ecSHeejin Ahn   // walk out to the nearest scope which isn't more deeply nested.
477e76fa9ecSHeejin Ahn   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
478e76fa9ecSHeejin Ahn     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
479e76fa9ecSHeejin Ahn       if (ScopeTop->getNumber() > Header->getNumber()) {
480e76fa9ecSHeejin Ahn         // Skip over an intervening scope.
4815c644c9bSHeejin Ahn         I = std::next(ScopeTop->getIterator());
482e76fa9ecSHeejin Ahn       } else {
483e76fa9ecSHeejin Ahn         // We found a scope level at an appropriate depth.
484e76fa9ecSHeejin Ahn         Header = ScopeTop;
485e76fa9ecSHeejin Ahn         break;
486e76fa9ecSHeejin Ahn       }
487e76fa9ecSHeejin Ahn     }
488e76fa9ecSHeejin Ahn   }
489e76fa9ecSHeejin Ahn 
490e76fa9ecSHeejin Ahn   // Decide where in Header to put the TRY.
491e76fa9ecSHeejin Ahn 
49244a5a4b1SHeejin Ahn   // Instructions that should go before the TRY.
493e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
49444a5a4b1SHeejin Ahn   // Instructions that should go after the TRY.
495e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
496e76fa9ecSHeejin Ahn   for (const auto &MI : *Header) {
49744a5a4b1SHeejin Ahn     // If there is a previously placed LOOP marker and the bottom block of the
49844a5a4b1SHeejin Ahn     // loop is above MBB, it should be after the TRY, because the loop is nested
49944a5a4b1SHeejin Ahn     // in this TRY. Otherwise it should be before the TRY.
500e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP) {
50144a5a4b1SHeejin Ahn       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
50244a5a4b1SHeejin Ahn       if (MBB.getNumber() > LoopBottom->getNumber())
503e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
504e76fa9ecSHeejin Ahn #ifndef NDEBUG
505e76fa9ecSHeejin Ahn       else
506e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
507e76fa9ecSHeejin Ahn #endif
508e76fa9ecSHeejin Ahn     }
509e76fa9ecSHeejin Ahn 
51044a5a4b1SHeejin Ahn     // All previously inserted BLOCK/TRY markers should be after the TRY because
51144a5a4b1SHeejin Ahn     // they are all nested trys.
51244a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::BLOCK ||
51344a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::TRY)
514e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
515e76fa9ecSHeejin Ahn 
516e76fa9ecSHeejin Ahn #ifndef NDEBUG
51744a5a4b1SHeejin Ahn     // All END_(BLOCK/LOOP/TRY) markers should be before the TRY.
51844a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
51944a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::END_LOOP ||
520e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY)
521e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
522e76fa9ecSHeejin Ahn #endif
523e76fa9ecSHeejin Ahn 
524e76fa9ecSHeejin Ahn     // Terminators should go after the TRY.
525e76fa9ecSHeejin Ahn     if (MI.isTerminator())
526e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
527e76fa9ecSHeejin Ahn   }
528e76fa9ecSHeejin Ahn 
529e76fa9ecSHeejin Ahn   // Local expression tree should go after the TRY.
530e76fa9ecSHeejin Ahn   for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
531e76fa9ecSHeejin Ahn        --I) {
532409b4391SYury Delendik     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
533409b4391SYury Delendik       continue;
534e76fa9ecSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
535e76fa9ecSHeejin Ahn       AfterSet.insert(&*std::prev(I));
536e76fa9ecSHeejin Ahn     else
537e76fa9ecSHeejin Ahn       break;
538e76fa9ecSHeejin Ahn   }
539e76fa9ecSHeejin Ahn 
540e76fa9ecSHeejin Ahn   // If Header unwinds to MBB (= Header contains 'invoke'), the try block should
541e76fa9ecSHeejin Ahn   // contain the call within it. So the call should go after the TRY. The
542e76fa9ecSHeejin Ahn   // exception is when the header's terminator is a rethrow instruction, in
543e76fa9ecSHeejin Ahn   // which case that instruction, not a call instruction before it, is gonna
544e76fa9ecSHeejin Ahn   // throw.
545e76fa9ecSHeejin Ahn   if (MBB.isPredecessor(Header)) {
546e76fa9ecSHeejin Ahn     auto TermPos = Header->getFirstTerminator();
547d6f48786SHeejin Ahn     if (TermPos == Header->end() ||
548d6f48786SHeejin Ahn         TermPos->getOpcode() != WebAssembly::RETHROW) {
549e76fa9ecSHeejin Ahn       for (const auto &MI : reverse(*Header)) {
550e76fa9ecSHeejin Ahn         if (MI.isCall()) {
551e76fa9ecSHeejin Ahn           AfterSet.insert(&MI);
5528b49b6beSHeejin Ahn           // Possibly throwing calls are usually wrapped by EH_LABEL
5538b49b6beSHeejin Ahn           // instructions. We don't want to split them and the call.
5548b49b6beSHeejin Ahn           if (MI.getIterator() != Header->begin() &&
5558b49b6beSHeejin Ahn               std::prev(MI.getIterator())->isEHLabel())
5568b49b6beSHeejin Ahn             AfterSet.insert(&*std::prev(MI.getIterator()));
557e76fa9ecSHeejin Ahn           break;
558e76fa9ecSHeejin Ahn         }
559e76fa9ecSHeejin Ahn       }
560e76fa9ecSHeejin Ahn     }
561e76fa9ecSHeejin Ahn   }
562e76fa9ecSHeejin Ahn 
563e76fa9ecSHeejin Ahn   // Add the TRY.
56418c56a07SHeejin Ahn   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
565e76fa9ecSHeejin Ahn   MachineInstr *Begin =
566e76fa9ecSHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
567e76fa9ecSHeejin Ahn               TII.get(WebAssembly::TRY))
568e76fa9ecSHeejin Ahn           .addImm(int64_t(WebAssembly::ExprType::Void));
569e76fa9ecSHeejin Ahn 
570e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_TRY.
571e76fa9ecSHeejin Ahn   BeforeSet.clear();
572e76fa9ecSHeejin Ahn   AfterSet.clear();
57320cf0749SHeejin Ahn   for (const auto &MI : *Cont) {
574e76fa9ecSHeejin Ahn #ifndef NDEBUG
57544a5a4b1SHeejin Ahn     // END_TRY should precede existing LOOP and BLOCK markers.
57644a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP ||
57744a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::BLOCK)
578e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
579e76fa9ecSHeejin Ahn 
580e76fa9ecSHeejin Ahn     // All END_TRY markers placed earlier belong to exceptions that contains
581e76fa9ecSHeejin Ahn     // this one.
582e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_TRY)
583e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
584e76fa9ecSHeejin Ahn #endif
585e76fa9ecSHeejin Ahn 
586e76fa9ecSHeejin Ahn     // If there is a previously placed END_LOOP marker and its header is after
587e76fa9ecSHeejin Ahn     // where TRY marker is, this loop is contained within the 'catch' part, so
588e76fa9ecSHeejin Ahn     // the END_TRY marker should go after that. Otherwise, the whole try-catch
589e76fa9ecSHeejin Ahn     // is contained within this loop, so the END_TRY should go before that.
590e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP) {
591222718fdSHeejin Ahn       // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they
592222718fdSHeejin Ahn       // are in the same BB, LOOP is always before TRY.
593222718fdSHeejin Ahn       if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber())
594e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
595e76fa9ecSHeejin Ahn #ifndef NDEBUG
596e76fa9ecSHeejin Ahn       else
597e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
598e76fa9ecSHeejin Ahn #endif
599e76fa9ecSHeejin Ahn     }
60044a5a4b1SHeejin Ahn 
60144a5a4b1SHeejin Ahn     // It is not possible for an END_BLOCK to be already in this block.
602e76fa9ecSHeejin Ahn   }
603e76fa9ecSHeejin Ahn 
604e76fa9ecSHeejin Ahn   // Mark the end of the TRY.
60520cf0749SHeejin Ahn   InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet);
606e76fa9ecSHeejin Ahn   MachineInstr *End =
60720cf0749SHeejin Ahn       BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(),
608e76fa9ecSHeejin Ahn               TII.get(WebAssembly::END_TRY));
609e76fa9ecSHeejin Ahn   registerTryScope(Begin, End, &MBB);
610e76fa9ecSHeejin Ahn 
61182da1ffcSHeejin Ahn   // Track the farthest-spanning scope that ends at this point. We create two
61282da1ffcSHeejin Ahn   // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB
61382da1ffcSHeejin Ahn   // with 'try'). We need to create 'catch' -> 'try' mapping here too because
61482da1ffcSHeejin Ahn   // markers should not span across 'catch'. For example, this should not
61582da1ffcSHeejin Ahn   // happen:
61682da1ffcSHeejin Ahn   //
61782da1ffcSHeejin Ahn   // try
61882da1ffcSHeejin Ahn   //   block     --|  (X)
61982da1ffcSHeejin Ahn   // catch         |
62082da1ffcSHeejin Ahn   //   end_block --|
62182da1ffcSHeejin Ahn   // end_try
62282da1ffcSHeejin Ahn   for (int Number : {Cont->getNumber(), MBB.getNumber()}) {
623e76fa9ecSHeejin Ahn     if (!ScopeTops[Number] ||
624e76fa9ecSHeejin Ahn         ScopeTops[Number]->getNumber() > Header->getNumber())
625e76fa9ecSHeejin Ahn       ScopeTops[Number] = Header;
626e76fa9ecSHeejin Ahn   }
62782da1ffcSHeejin Ahn }
628e76fa9ecSHeejin Ahn 
629cf699b45SHeejin Ahn void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) {
630cf699b45SHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
631cf699b45SHeejin Ahn 
632cf699b45SHeejin Ahn   // When there is an unconditional branch right before a catch instruction and
633cf699b45SHeejin Ahn   // it branches to the end of end_try marker, we don't need the branch, because
634cf699b45SHeejin Ahn   // it there is no exception, the control flow transfers to that point anyway.
635cf699b45SHeejin Ahn   // bb0:
636cf699b45SHeejin Ahn   //   try
637cf699b45SHeejin Ahn   //     ...
638cf699b45SHeejin Ahn   //     br bb2      <- Not necessary
639cf699b45SHeejin Ahn   // bb1:
640cf699b45SHeejin Ahn   //   catch
641cf699b45SHeejin Ahn   //     ...
642cf699b45SHeejin Ahn   // bb2:
643cf699b45SHeejin Ahn   //   end
644cf699b45SHeejin Ahn   for (auto &MBB : MF) {
645cf699b45SHeejin Ahn     if (!MBB.isEHPad())
646cf699b45SHeejin Ahn       continue;
647cf699b45SHeejin Ahn 
648cf699b45SHeejin Ahn     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
649cf699b45SHeejin Ahn     SmallVector<MachineOperand, 4> Cond;
6505c644c9bSHeejin Ahn     MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode();
651cf699b45SHeejin Ahn     MachineBasicBlock *Cont = BeginToEnd[EHPadToTry[&MBB]]->getParent();
652cf699b45SHeejin Ahn     bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond);
653cf699b45SHeejin Ahn     if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) ||
654cf699b45SHeejin Ahn                        (!Cond.empty() && FBB && FBB == Cont)))
655cf699b45SHeejin Ahn       TII.removeBranch(*EHPadLayoutPred);
656cf699b45SHeejin Ahn   }
657cf699b45SHeejin Ahn 
658cf699b45SHeejin Ahn   // When there are block / end_block markers that overlap with try / end_try
659cf699b45SHeejin Ahn   // markers, and the block and try markers' return types are the same, the
660cf699b45SHeejin Ahn   // block /end_block markers are not necessary, because try / end_try markers
661cf699b45SHeejin Ahn   // also can serve as boundaries for branches.
662cf699b45SHeejin Ahn   // block         <- Not necessary
663cf699b45SHeejin Ahn   //   try
664cf699b45SHeejin Ahn   //     ...
665cf699b45SHeejin Ahn   //   catch
666cf699b45SHeejin Ahn   //     ...
667cf699b45SHeejin Ahn   //   end
668cf699b45SHeejin Ahn   // end           <- Not necessary
669cf699b45SHeejin Ahn   SmallVector<MachineInstr *, 32> ToDelete;
670cf699b45SHeejin Ahn   for (auto &MBB : MF) {
671cf699b45SHeejin Ahn     for (auto &MI : MBB) {
672cf699b45SHeejin Ahn       if (MI.getOpcode() != WebAssembly::TRY)
673cf699b45SHeejin Ahn         continue;
674cf699b45SHeejin Ahn 
675cf699b45SHeejin Ahn       MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try];
676cf699b45SHeejin Ahn       MachineBasicBlock *TryBB = Try->getParent();
677cf699b45SHeejin Ahn       MachineBasicBlock *Cont = EndTry->getParent();
678cf699b45SHeejin Ahn       int64_t RetType = Try->getOperand(0).getImm();
6795c644c9bSHeejin Ahn       for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator());
680cf699b45SHeejin Ahn            B != TryBB->begin() && E != Cont->end() &&
681cf699b45SHeejin Ahn            std::prev(B)->getOpcode() == WebAssembly::BLOCK &&
682cf699b45SHeejin Ahn            E->getOpcode() == WebAssembly::END_BLOCK &&
683cf699b45SHeejin Ahn            std::prev(B)->getOperand(0).getImm() == RetType;
684cf699b45SHeejin Ahn            --B, ++E) {
685cf699b45SHeejin Ahn         ToDelete.push_back(&*std::prev(B));
686cf699b45SHeejin Ahn         ToDelete.push_back(&*E);
687cf699b45SHeejin Ahn       }
688cf699b45SHeejin Ahn     }
689cf699b45SHeejin Ahn   }
690cf699b45SHeejin Ahn   for (auto *MI : ToDelete) {
691cf699b45SHeejin Ahn     if (MI->getOpcode() == WebAssembly::BLOCK)
692cf699b45SHeejin Ahn       unregisterScope(MI);
693cf699b45SHeejin Ahn     MI->eraseFromParent();
694cf699b45SHeejin Ahn   }
695cf699b45SHeejin Ahn }
696cf699b45SHeejin Ahn 
697*c4ac74fbSHeejin Ahn bool WebAssemblyCFGStackify::fixUnwindMismatches(MachineFunction &MF) {
698*c4ac74fbSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
699*c4ac74fbSHeejin Ahn   MachineRegisterInfo &MRI = MF.getRegInfo();
700*c4ac74fbSHeejin Ahn 
701*c4ac74fbSHeejin Ahn   // Linearizing the control flow by placing TRY / END_TRY markers can create
702*c4ac74fbSHeejin Ahn   // mismatches in unwind destinations. There are two kinds of mismatches we
703*c4ac74fbSHeejin Ahn   // try to solve here.
704*c4ac74fbSHeejin Ahn 
705*c4ac74fbSHeejin Ahn   // 1. When an instruction may throw, but the EH pad it will unwind to can be
706*c4ac74fbSHeejin Ahn   //    different from the original CFG.
707*c4ac74fbSHeejin Ahn   //
708*c4ac74fbSHeejin Ahn   // Example: we have the following CFG:
709*c4ac74fbSHeejin Ahn   // bb0:
710*c4ac74fbSHeejin Ahn   //   call @foo (if it throws, unwind to bb2)
711*c4ac74fbSHeejin Ahn   // bb1:
712*c4ac74fbSHeejin Ahn   //   call @bar (if it throws, unwind to bb3)
713*c4ac74fbSHeejin Ahn   // bb2 (ehpad):
714*c4ac74fbSHeejin Ahn   //   catch
715*c4ac74fbSHeejin Ahn   //   ...
716*c4ac74fbSHeejin Ahn   // bb3 (ehpad)
717*c4ac74fbSHeejin Ahn   //   catch
718*c4ac74fbSHeejin Ahn   //   handler body
719*c4ac74fbSHeejin Ahn   //
720*c4ac74fbSHeejin Ahn   // And the CFG is sorted in this order. Then after placing TRY markers, it
721*c4ac74fbSHeejin Ahn   // will look like: (BB markers are omitted)
722*c4ac74fbSHeejin Ahn   // try $label1
723*c4ac74fbSHeejin Ahn   //   try
724*c4ac74fbSHeejin Ahn   //     call @foo
725*c4ac74fbSHeejin Ahn   //     call @bar   (if it throws, unwind to bb3)
726*c4ac74fbSHeejin Ahn   //   catch         <- ehpad (bb2)
727*c4ac74fbSHeejin Ahn   //     ...
728*c4ac74fbSHeejin Ahn   //   end_try
729*c4ac74fbSHeejin Ahn   // catch           <- ehpad (bb3)
730*c4ac74fbSHeejin Ahn   //   handler body
731*c4ac74fbSHeejin Ahn   // end_try
732*c4ac74fbSHeejin Ahn   //
733*c4ac74fbSHeejin Ahn   // Now if bar() throws, it is going to end up ip in bb2, not bb3, where it
734*c4ac74fbSHeejin Ahn   // is supposed to end up. We solve this problem by
735*c4ac74fbSHeejin Ahn   // a. Split the target unwind EH pad (here bb3) so that the handler body is
736*c4ac74fbSHeejin Ahn   //    right after 'end_try', which means we extract the handler body out of
737*c4ac74fbSHeejin Ahn   //    the catch block. We do this because this handler body should be
738*c4ac74fbSHeejin Ahn   //    somewhere branch-eable from the inner scope.
739*c4ac74fbSHeejin Ahn   // b. Wrap the call that has an incorrect unwind destination ('call @bar'
740*c4ac74fbSHeejin Ahn   //    here) with a nested try/catch/end_try scope, and within the new catch
741*c4ac74fbSHeejin Ahn   //    block, branches to the handler body.
742*c4ac74fbSHeejin Ahn   // c. Place a branch after the newly inserted nested end_try so it can bypass
743*c4ac74fbSHeejin Ahn   //    the handler body, which is now outside of a catch block.
744*c4ac74fbSHeejin Ahn   //
745*c4ac74fbSHeejin Ahn   // The result will like as follows. (new: a) means this instruction is newly
746*c4ac74fbSHeejin Ahn   // created in the process of doing 'a' above.
747*c4ac74fbSHeejin Ahn   //
748*c4ac74fbSHeejin Ahn   // block $label0                 (new: placeBlockMarker)
749*c4ac74fbSHeejin Ahn   //   try $label1
750*c4ac74fbSHeejin Ahn   //     try
751*c4ac74fbSHeejin Ahn   //       call @foo
752*c4ac74fbSHeejin Ahn   //       try                     (new: b)
753*c4ac74fbSHeejin Ahn   //         call @bar
754*c4ac74fbSHeejin Ahn   //       catch                   (new: b)
755*c4ac74fbSHeejin Ahn   //         local.set n / drop    (new: b)
756*c4ac74fbSHeejin Ahn   //         br $label1            (new: b)
757*c4ac74fbSHeejin Ahn   //       end_try                 (new: b)
758*c4ac74fbSHeejin Ahn   //     catch                     <- ehpad (bb2)
759*c4ac74fbSHeejin Ahn   //     end_try
760*c4ac74fbSHeejin Ahn   //     br $label0                (new: c)
761*c4ac74fbSHeejin Ahn   //   catch                       <- ehpad (bb3)
762*c4ac74fbSHeejin Ahn   //   end_try                     (hoisted: a)
763*c4ac74fbSHeejin Ahn   //   handler body
764*c4ac74fbSHeejin Ahn   // end_block                     (new: placeBlockMarker)
765*c4ac74fbSHeejin Ahn   //
766*c4ac74fbSHeejin Ahn   // Note that the new wrapping block/end_block will be generated later in
767*c4ac74fbSHeejin Ahn   // placeBlockMarker.
768*c4ac74fbSHeejin Ahn   //
769*c4ac74fbSHeejin Ahn   // TODO Currently local.set and local.gets are generated to move except_ref
770*c4ac74fbSHeejin Ahn   // value created by catches. That's because we don't support yielding values
771*c4ac74fbSHeejin Ahn   // from a block in LLVM machine IR yet, even though it is supported by wasm.
772*c4ac74fbSHeejin Ahn   // Delete unnecessary local.get/local.sets once yielding values from a block
773*c4ac74fbSHeejin Ahn   // is supported. The full EH spec requires multi-value support to do this, but
774*c4ac74fbSHeejin Ahn   // for C++ we don't yet need it because we only throw a single i32.
775*c4ac74fbSHeejin Ahn   //
776*c4ac74fbSHeejin Ahn   // ---
777*c4ac74fbSHeejin Ahn   // 2. The same as 1, but in this case an instruction unwinds to a caller
778*c4ac74fbSHeejin Ahn   //    function and not another EH pad.
779*c4ac74fbSHeejin Ahn   //
780*c4ac74fbSHeejin Ahn   // Example: we have the following CFG:
781*c4ac74fbSHeejin Ahn   // bb0:
782*c4ac74fbSHeejin Ahn   //   call @foo (if it throws, unwind to bb2)
783*c4ac74fbSHeejin Ahn   // bb1:
784*c4ac74fbSHeejin Ahn   //   call @bar (if it throws, unwind to caller)
785*c4ac74fbSHeejin Ahn   // bb2 (ehpad):
786*c4ac74fbSHeejin Ahn   //   catch
787*c4ac74fbSHeejin Ahn   //   ...
788*c4ac74fbSHeejin Ahn   //
789*c4ac74fbSHeejin Ahn   // And the CFG is sorted in this order. Then after placing TRY markers, it
790*c4ac74fbSHeejin Ahn   // will look like:
791*c4ac74fbSHeejin Ahn   // try
792*c4ac74fbSHeejin Ahn   //   call @foo
793*c4ac74fbSHeejin Ahn   //   call @bar   (if it throws, unwind to caller)
794*c4ac74fbSHeejin Ahn   // catch         <- ehpad (bb2)
795*c4ac74fbSHeejin Ahn   //   ...
796*c4ac74fbSHeejin Ahn   // end_try
797*c4ac74fbSHeejin Ahn   //
798*c4ac74fbSHeejin Ahn   // Now if bar() throws, it is going to end up ip in bb2, when it is supposed
799*c4ac74fbSHeejin Ahn   // throw up to the caller.
800*c4ac74fbSHeejin Ahn   // We solve this problem by
801*c4ac74fbSHeejin Ahn   // a. Create a new 'appendix' BB at the end of the function and put a single
802*c4ac74fbSHeejin Ahn   //    'rethrow' instruction (+ local.get) in there.
803*c4ac74fbSHeejin Ahn   // b. Wrap the call that has an incorrect unwind destination ('call @bar'
804*c4ac74fbSHeejin Ahn   //    here) with a nested try/catch/end_try scope, and within the new catch
805*c4ac74fbSHeejin Ahn   //    block, branches to the new appendix block.
806*c4ac74fbSHeejin Ahn   //
807*c4ac74fbSHeejin Ahn   // block $label0          (new: placeBlockMarker)
808*c4ac74fbSHeejin Ahn   //   try
809*c4ac74fbSHeejin Ahn   //     call @foo
810*c4ac74fbSHeejin Ahn   //     try                (new: b)
811*c4ac74fbSHeejin Ahn   //       call @bar
812*c4ac74fbSHeejin Ahn   //     catch              (new: b)
813*c4ac74fbSHeejin Ahn   //       local.set n      (new: b)
814*c4ac74fbSHeejin Ahn   //       br $label0       (new: b)
815*c4ac74fbSHeejin Ahn   //     end_try            (new: b)
816*c4ac74fbSHeejin Ahn   //   catch                <- ehpad (bb2)
817*c4ac74fbSHeejin Ahn   //     ...
818*c4ac74fbSHeejin Ahn   //   end_try
819*c4ac74fbSHeejin Ahn   // ...
820*c4ac74fbSHeejin Ahn   // end_block              (new: placeBlockMarker)
821*c4ac74fbSHeejin Ahn   // local.get n            (new: a)  <- appendix block
822*c4ac74fbSHeejin Ahn   // rethrow                (new: a)
823*c4ac74fbSHeejin Ahn   //
824*c4ac74fbSHeejin Ahn   // In case there are multiple calls in a BB that may throw to the caller, they
825*c4ac74fbSHeejin Ahn   // can be wrapped together in one nested try scope. (In 1, this couldn't
826*c4ac74fbSHeejin Ahn   // happen, because may-throwing instruction there had an unwind destination,
827*c4ac74fbSHeejin Ahn   // i.e., it was an invoke before, and there could be only one invoke within a
828*c4ac74fbSHeejin Ahn   // BB.)
829*c4ac74fbSHeejin Ahn 
830*c4ac74fbSHeejin Ahn   SmallVector<const MachineBasicBlock *, 8> EHPadStack;
831*c4ac74fbSHeejin Ahn   // Range of intructions to be wrapped in a new nested try/catch
832*c4ac74fbSHeejin Ahn   using TryRange = std::pair<MachineInstr *, MachineInstr *>;
833*c4ac74fbSHeejin Ahn   // In original CFG, <unwind destionation BB, a vector of try ranges>
834*c4ac74fbSHeejin Ahn   DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> UnwindDestToTryRanges;
835*c4ac74fbSHeejin Ahn   // In new CFG, <destination to branch to, a vector of try ranges>
836*c4ac74fbSHeejin Ahn   DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> BrDestToTryRanges;
837*c4ac74fbSHeejin Ahn   // In new CFG, <destination to branch to, register containing except_ref>
838*c4ac74fbSHeejin Ahn   DenseMap<MachineBasicBlock *, unsigned> BrDestToExnReg;
839*c4ac74fbSHeejin Ahn 
840*c4ac74fbSHeejin Ahn   // Gather possibly throwing calls (i.e., previously invokes) whose current
841*c4ac74fbSHeejin Ahn   // unwind destination is not the same as the original CFG.
842*c4ac74fbSHeejin Ahn   for (auto &MBB : reverse(MF)) {
843*c4ac74fbSHeejin Ahn     bool SeenThrowableInstInBB = false;
844*c4ac74fbSHeejin Ahn     for (auto &MI : reverse(MBB)) {
845*c4ac74fbSHeejin Ahn       if (MI.getOpcode() == WebAssembly::TRY)
846*c4ac74fbSHeejin Ahn         EHPadStack.pop_back();
847*c4ac74fbSHeejin Ahn       else if (MI.getOpcode() == WebAssembly::CATCH)
848*c4ac74fbSHeejin Ahn         EHPadStack.push_back(MI.getParent());
849*c4ac74fbSHeejin Ahn 
850*c4ac74fbSHeejin Ahn       // In this loop we only gather calls that have an EH pad to unwind. So
851*c4ac74fbSHeejin Ahn       // there will be at most 1 such call (= invoke) in a BB, so after we've
852*c4ac74fbSHeejin Ahn       // seen one, we can skip the rest of BB. Also if MBB has no EH pad
853*c4ac74fbSHeejin Ahn       // successor or MI does not throw, this is not an invoke.
854*c4ac74fbSHeejin Ahn       if (SeenThrowableInstInBB || !MBB.hasEHPadSuccessor() ||
855*c4ac74fbSHeejin Ahn           !WebAssembly::mayThrow(MI))
856*c4ac74fbSHeejin Ahn         continue;
857*c4ac74fbSHeejin Ahn       SeenThrowableInstInBB = true;
858*c4ac74fbSHeejin Ahn 
859*c4ac74fbSHeejin Ahn       // If the EH pad on the stack top is where this instruction should unwind
860*c4ac74fbSHeejin Ahn       // next, we're good.
861*c4ac74fbSHeejin Ahn       MachineBasicBlock *UnwindDest = nullptr;
862*c4ac74fbSHeejin Ahn       for (auto *Succ : MBB.successors()) {
863*c4ac74fbSHeejin Ahn         if (Succ->isEHPad()) {
864*c4ac74fbSHeejin Ahn           UnwindDest = Succ;
865*c4ac74fbSHeejin Ahn           break;
866*c4ac74fbSHeejin Ahn         }
867*c4ac74fbSHeejin Ahn       }
868*c4ac74fbSHeejin Ahn       if (EHPadStack.back() == UnwindDest)
869*c4ac74fbSHeejin Ahn         continue;
870*c4ac74fbSHeejin Ahn 
871*c4ac74fbSHeejin Ahn       // If not, record the range.
872*c4ac74fbSHeejin Ahn       UnwindDestToTryRanges[UnwindDest].push_back(TryRange(&MI, &MI));
873*c4ac74fbSHeejin Ahn     }
874*c4ac74fbSHeejin Ahn   }
875*c4ac74fbSHeejin Ahn 
876*c4ac74fbSHeejin Ahn   assert(EHPadStack.empty());
877*c4ac74fbSHeejin Ahn 
878*c4ac74fbSHeejin Ahn   // Gather possibly throwing calls that are supposed to unwind up to the caller
879*c4ac74fbSHeejin Ahn   // if they throw, but currently unwind to an incorrect destination. Unlike the
880*c4ac74fbSHeejin Ahn   // loop above, there can be multiple calls within a BB that unwind to the
881*c4ac74fbSHeejin Ahn   // caller, which we should group together in a range.
882*c4ac74fbSHeejin Ahn   bool NeedAppendixBlock = false;
883*c4ac74fbSHeejin Ahn   for (auto &MBB : reverse(MF)) {
884*c4ac74fbSHeejin Ahn     MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; // inclusive
885*c4ac74fbSHeejin Ahn     for (auto &MI : reverse(MBB)) {
886*c4ac74fbSHeejin Ahn       if (MI.getOpcode() == WebAssembly::TRY)
887*c4ac74fbSHeejin Ahn         EHPadStack.pop_back();
888*c4ac74fbSHeejin Ahn       else if (MI.getOpcode() == WebAssembly::CATCH)
889*c4ac74fbSHeejin Ahn         EHPadStack.push_back(MI.getParent());
890*c4ac74fbSHeejin Ahn 
891*c4ac74fbSHeejin Ahn       // If MBB has an EH pad successor, this inst does not unwind to caller.
892*c4ac74fbSHeejin Ahn       if (MBB.hasEHPadSuccessor())
893*c4ac74fbSHeejin Ahn         continue;
894*c4ac74fbSHeejin Ahn 
895*c4ac74fbSHeejin Ahn       // We wrap up the current range when we see a marker even if we haven't
896*c4ac74fbSHeejin Ahn       // finished a BB.
897*c4ac74fbSHeejin Ahn       if (RangeEnd && WebAssembly::isMarker(MI)) {
898*c4ac74fbSHeejin Ahn         NeedAppendixBlock = true;
899*c4ac74fbSHeejin Ahn         // Record the range. nullptr here means the unwind destination is the
900*c4ac74fbSHeejin Ahn         // caller.
901*c4ac74fbSHeejin Ahn         UnwindDestToTryRanges[nullptr].push_back(
902*c4ac74fbSHeejin Ahn             TryRange(RangeBegin, RangeEnd));
903*c4ac74fbSHeejin Ahn         RangeBegin = RangeEnd = nullptr; // Reset range pointers
904*c4ac74fbSHeejin Ahn       }
905*c4ac74fbSHeejin Ahn 
906*c4ac74fbSHeejin Ahn       // If EHPadStack is empty, that means it is correctly unwind to caller if
907*c4ac74fbSHeejin Ahn       // it throws, so we're good. If MI does not throw, we're good too.
908*c4ac74fbSHeejin Ahn       if (EHPadStack.empty() || !WebAssembly::mayThrow(MI))
909*c4ac74fbSHeejin Ahn         continue;
910*c4ac74fbSHeejin Ahn 
911*c4ac74fbSHeejin Ahn       // We found an instruction that unwinds to the caller but currently has an
912*c4ac74fbSHeejin Ahn       // incorrect unwind destination. Create a new range or increment the
913*c4ac74fbSHeejin Ahn       // currently existing range.
914*c4ac74fbSHeejin Ahn       if (!RangeEnd)
915*c4ac74fbSHeejin Ahn         RangeBegin = RangeEnd = &MI;
916*c4ac74fbSHeejin Ahn       else
917*c4ac74fbSHeejin Ahn         RangeBegin = &MI;
918*c4ac74fbSHeejin Ahn     }
919*c4ac74fbSHeejin Ahn 
920*c4ac74fbSHeejin Ahn     if (RangeEnd) {
921*c4ac74fbSHeejin Ahn       NeedAppendixBlock = true;
922*c4ac74fbSHeejin Ahn       // Record the range. nullptr here means the unwind destination is the
923*c4ac74fbSHeejin Ahn       // caller.
924*c4ac74fbSHeejin Ahn       UnwindDestToTryRanges[nullptr].push_back(TryRange(RangeBegin, RangeEnd));
925*c4ac74fbSHeejin Ahn       RangeBegin = RangeEnd = nullptr; // Reset range pointers
926*c4ac74fbSHeejin Ahn     }
927*c4ac74fbSHeejin Ahn   }
928*c4ac74fbSHeejin Ahn 
929*c4ac74fbSHeejin Ahn   assert(EHPadStack.empty());
930*c4ac74fbSHeejin Ahn   // We don't have any unwind destination mismatches to resolve.
931*c4ac74fbSHeejin Ahn   if (UnwindDestToTryRanges.empty())
932*c4ac74fbSHeejin Ahn     return false;
933*c4ac74fbSHeejin Ahn 
934*c4ac74fbSHeejin Ahn   // If we found instructions that should unwind to the caller but currently
935*c4ac74fbSHeejin Ahn   // have incorrect unwind destination, we create an appendix block at the end
936*c4ac74fbSHeejin Ahn   // of the function with a local.get and a rethrow instruction.
937*c4ac74fbSHeejin Ahn   if (NeedAppendixBlock) {
938*c4ac74fbSHeejin Ahn     auto *AppendixBB = getAppendixBlock(MF);
939*c4ac74fbSHeejin Ahn     unsigned ExnReg =
940*c4ac74fbSHeejin Ahn         MRI.createVirtualRegister(&WebAssembly::EXCEPT_REFRegClass);
941*c4ac74fbSHeejin Ahn     BuildMI(AppendixBB, DebugLoc(), TII.get(WebAssembly::RETHROW))
942*c4ac74fbSHeejin Ahn         .addReg(ExnReg);
943*c4ac74fbSHeejin Ahn     // These instruction ranges should branch to this appendix BB.
944*c4ac74fbSHeejin Ahn     for (auto Range : UnwindDestToTryRanges[nullptr])
945*c4ac74fbSHeejin Ahn       BrDestToTryRanges[AppendixBB].push_back(Range);
946*c4ac74fbSHeejin Ahn     BrDestToExnReg[AppendixBB] = ExnReg;
947*c4ac74fbSHeejin Ahn   }
948*c4ac74fbSHeejin Ahn 
949*c4ac74fbSHeejin Ahn   // We loop through unwind destination EH pads that are targeted from some
950*c4ac74fbSHeejin Ahn   // inner scopes. Because these EH pads are destination of more than one scope
951*c4ac74fbSHeejin Ahn   // now, we split them so that the handler body is after 'end_try'.
952*c4ac74fbSHeejin Ahn   // - Before
953*c4ac74fbSHeejin Ahn   // ehpad:
954*c4ac74fbSHeejin Ahn   //   catch
955*c4ac74fbSHeejin Ahn   //   local.set n / drop
956*c4ac74fbSHeejin Ahn   //   handler body
957*c4ac74fbSHeejin Ahn   // ...
958*c4ac74fbSHeejin Ahn   // cont:
959*c4ac74fbSHeejin Ahn   //   end_try
960*c4ac74fbSHeejin Ahn   //
961*c4ac74fbSHeejin Ahn   // - After
962*c4ac74fbSHeejin Ahn   // ehpad:
963*c4ac74fbSHeejin Ahn   //   catch
964*c4ac74fbSHeejin Ahn   //   local.set n / drop
965*c4ac74fbSHeejin Ahn   // brdest:               (new)
966*c4ac74fbSHeejin Ahn   //   end_try             (hoisted from 'cont' BB)
967*c4ac74fbSHeejin Ahn   //   handler body        (taken from 'ehpad')
968*c4ac74fbSHeejin Ahn   // ...
969*c4ac74fbSHeejin Ahn   // cont:
970*c4ac74fbSHeejin Ahn   for (auto &P : UnwindDestToTryRanges) {
971*c4ac74fbSHeejin Ahn     NumUnwindMismatches++;
972*c4ac74fbSHeejin Ahn 
973*c4ac74fbSHeejin Ahn     // This means the destination is the appendix BB, which was separately
974*c4ac74fbSHeejin Ahn     // handled above.
975*c4ac74fbSHeejin Ahn     if (!P.first)
976*c4ac74fbSHeejin Ahn       continue;
977*c4ac74fbSHeejin Ahn 
978*c4ac74fbSHeejin Ahn     MachineBasicBlock *EHPad = P.first;
979*c4ac74fbSHeejin Ahn 
980*c4ac74fbSHeejin Ahn     // Find 'catch' and 'local.set' or 'drop' instruction that follows the
981*c4ac74fbSHeejin Ahn     // 'catch'. If -wasm-disable-explicit-locals is not set, 'catch' should be
982*c4ac74fbSHeejin Ahn     // always followed by either 'local.set' or a 'drop', because 'br_on_exn' is
983*c4ac74fbSHeejin Ahn     // generated after 'catch' in LateEHPrepare and we don't support blocks
984*c4ac74fbSHeejin Ahn     // taking values yet.
985*c4ac74fbSHeejin Ahn     MachineInstr *Catch = nullptr;
986*c4ac74fbSHeejin Ahn     unsigned ExnReg = 0;
987*c4ac74fbSHeejin Ahn     for (auto &MI : *EHPad) {
988*c4ac74fbSHeejin Ahn       switch (MI.getOpcode()) {
989*c4ac74fbSHeejin Ahn       case WebAssembly::CATCH:
990*c4ac74fbSHeejin Ahn         Catch = &MI;
991*c4ac74fbSHeejin Ahn         ExnReg = Catch->getOperand(0).getReg();
992*c4ac74fbSHeejin Ahn         break;
993*c4ac74fbSHeejin Ahn       }
994*c4ac74fbSHeejin Ahn     }
995*c4ac74fbSHeejin Ahn     assert(Catch && "EH pad does not have a catch");
996*c4ac74fbSHeejin Ahn     assert(ExnReg != 0 && "Invalid register");
997*c4ac74fbSHeejin Ahn 
998*c4ac74fbSHeejin Ahn     auto SplitPos = std::next(Catch->getIterator());
999*c4ac74fbSHeejin Ahn 
1000*c4ac74fbSHeejin Ahn     // Create a new BB that's gonna be the destination for branches from the
1001*c4ac74fbSHeejin Ahn     // inner mismatched scope.
1002*c4ac74fbSHeejin Ahn     MachineInstr *BeginTry = EHPadToTry[EHPad];
1003*c4ac74fbSHeejin Ahn     MachineInstr *EndTry = BeginToEnd[BeginTry];
1004*c4ac74fbSHeejin Ahn     MachineBasicBlock *Cont = EndTry->getParent();
1005*c4ac74fbSHeejin Ahn     auto *BrDest = MF.CreateMachineBasicBlock();
1006*c4ac74fbSHeejin Ahn     MF.insert(std::next(EHPad->getIterator()), BrDest);
1007*c4ac74fbSHeejin Ahn     // Hoist up the existing 'end_try'.
1008*c4ac74fbSHeejin Ahn     BrDest->insert(BrDest->end(), EndTry->removeFromParent());
1009*c4ac74fbSHeejin Ahn     // Take out the handler body from EH pad to the new branch destination BB.
1010*c4ac74fbSHeejin Ahn     BrDest->splice(BrDest->end(), EHPad, SplitPos, EHPad->end());
1011*c4ac74fbSHeejin Ahn     // Fix predecessor-successor relationship.
1012*c4ac74fbSHeejin Ahn     BrDest->transferSuccessors(EHPad);
1013*c4ac74fbSHeejin Ahn     EHPad->addSuccessor(BrDest);
1014*c4ac74fbSHeejin Ahn 
1015*c4ac74fbSHeejin Ahn     // All try ranges that were supposed to unwind to this EH pad now have to
1016*c4ac74fbSHeejin Ahn     // branch to this new branch dest BB.
1017*c4ac74fbSHeejin Ahn     for (auto Range : UnwindDestToTryRanges[EHPad])
1018*c4ac74fbSHeejin Ahn       BrDestToTryRanges[BrDest].push_back(Range);
1019*c4ac74fbSHeejin Ahn     BrDestToExnReg[BrDest] = ExnReg;
1020*c4ac74fbSHeejin Ahn 
1021*c4ac74fbSHeejin Ahn     // In case we fall through to the continuation BB after the catch block, we
1022*c4ac74fbSHeejin Ahn     // now have to add a branch to it.
1023*c4ac74fbSHeejin Ahn     // - Before
1024*c4ac74fbSHeejin Ahn     // try
1025*c4ac74fbSHeejin Ahn     //   ...
1026*c4ac74fbSHeejin Ahn     //   (falls through to 'cont')
1027*c4ac74fbSHeejin Ahn     // catch
1028*c4ac74fbSHeejin Ahn     //   handler body
1029*c4ac74fbSHeejin Ahn     // end
1030*c4ac74fbSHeejin Ahn     //               <-- cont
1031*c4ac74fbSHeejin Ahn     //
1032*c4ac74fbSHeejin Ahn     // - After
1033*c4ac74fbSHeejin Ahn     // try
1034*c4ac74fbSHeejin Ahn     //   ...
1035*c4ac74fbSHeejin Ahn     //   br %cont    (new)
1036*c4ac74fbSHeejin Ahn     // catch
1037*c4ac74fbSHeejin Ahn     // end
1038*c4ac74fbSHeejin Ahn     // handler body
1039*c4ac74fbSHeejin Ahn     //               <-- cont
1040*c4ac74fbSHeejin Ahn     MachineBasicBlock *EHPadLayoutPred = &*std::prev(EHPad->getIterator());
1041*c4ac74fbSHeejin Ahn     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1042*c4ac74fbSHeejin Ahn     SmallVector<MachineOperand, 4> Cond;
1043*c4ac74fbSHeejin Ahn     bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond);
1044*c4ac74fbSHeejin Ahn     if (Analyzable && !TBB && !FBB) {
1045*c4ac74fbSHeejin Ahn       DebugLoc DL = EHPadLayoutPred->empty()
1046*c4ac74fbSHeejin Ahn                         ? DebugLoc()
1047*c4ac74fbSHeejin Ahn                         : EHPadLayoutPred->rbegin()->getDebugLoc();
1048*c4ac74fbSHeejin Ahn       BuildMI(EHPadLayoutPred, DL, TII.get(WebAssembly::BR)).addMBB(Cont);
1049*c4ac74fbSHeejin Ahn     }
1050*c4ac74fbSHeejin Ahn   }
1051*c4ac74fbSHeejin Ahn 
1052*c4ac74fbSHeejin Ahn   // For possibly throwing calls whose unwind destinations are currently
1053*c4ac74fbSHeejin Ahn   // incorrect because of CFG linearization, we wrap them with a nested
1054*c4ac74fbSHeejin Ahn   // try/catch/end_try, and within the new catch block, we branch to the correct
1055*c4ac74fbSHeejin Ahn   // handler.
1056*c4ac74fbSHeejin Ahn   // - Before
1057*c4ac74fbSHeejin Ahn   // mbb:
1058*c4ac74fbSHeejin Ahn   //   call @foo       <- Unwind destination mismatch!
1059*c4ac74fbSHeejin Ahn   // ehpad:
1060*c4ac74fbSHeejin Ahn   //   ...
1061*c4ac74fbSHeejin Ahn   //
1062*c4ac74fbSHeejin Ahn   // - After
1063*c4ac74fbSHeejin Ahn   // mbb:
1064*c4ac74fbSHeejin Ahn   //   try                (new)
1065*c4ac74fbSHeejin Ahn   //   call @foo
1066*c4ac74fbSHeejin Ahn   // nested-ehpad:        (new)
1067*c4ac74fbSHeejin Ahn   //   catch              (new)
1068*c4ac74fbSHeejin Ahn   //   local.set n / drop (new)
1069*c4ac74fbSHeejin Ahn   //   br %brdest         (new)
1070*c4ac74fbSHeejin Ahn   // nested-end:          (new)
1071*c4ac74fbSHeejin Ahn   //   end_try            (new)
1072*c4ac74fbSHeejin Ahn   // ehpad:
1073*c4ac74fbSHeejin Ahn   //   ...
1074*c4ac74fbSHeejin Ahn   for (auto &P : BrDestToTryRanges) {
1075*c4ac74fbSHeejin Ahn     MachineBasicBlock *BrDest = P.first;
1076*c4ac74fbSHeejin Ahn     auto &TryRanges = P.second;
1077*c4ac74fbSHeejin Ahn     unsigned ExnReg = BrDestToExnReg[BrDest];
1078*c4ac74fbSHeejin Ahn 
1079*c4ac74fbSHeejin Ahn     for (auto Range : TryRanges) {
1080*c4ac74fbSHeejin Ahn       MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr;
1081*c4ac74fbSHeejin Ahn       std::tie(RangeBegin, RangeEnd) = Range;
1082*c4ac74fbSHeejin Ahn       auto *MBB = RangeBegin->getParent();
1083*c4ac74fbSHeejin Ahn 
1084*c4ac74fbSHeejin Ahn       // Include possible EH_LABELs in the range
1085*c4ac74fbSHeejin Ahn       if (RangeBegin->getIterator() != MBB->begin() &&
1086*c4ac74fbSHeejin Ahn           std::prev(RangeBegin->getIterator())->isEHLabel())
1087*c4ac74fbSHeejin Ahn         RangeBegin = &*std::prev(RangeBegin->getIterator());
1088*c4ac74fbSHeejin Ahn       if (std::next(RangeEnd->getIterator()) != MBB->end() &&
1089*c4ac74fbSHeejin Ahn           std::next(RangeEnd->getIterator())->isEHLabel())
1090*c4ac74fbSHeejin Ahn         RangeEnd = &*std::next(RangeEnd->getIterator());
1091*c4ac74fbSHeejin Ahn 
1092*c4ac74fbSHeejin Ahn       MachineBasicBlock *EHPad = nullptr;
1093*c4ac74fbSHeejin Ahn       for (auto *Succ : MBB->successors()) {
1094*c4ac74fbSHeejin Ahn         if (Succ->isEHPad()) {
1095*c4ac74fbSHeejin Ahn           EHPad = Succ;
1096*c4ac74fbSHeejin Ahn           break;
1097*c4ac74fbSHeejin Ahn         }
1098*c4ac74fbSHeejin Ahn       }
1099*c4ac74fbSHeejin Ahn 
1100*c4ac74fbSHeejin Ahn       // Create the nested try instruction.
1101*c4ac74fbSHeejin Ahn       MachineInstr *NestedTry =
1102*c4ac74fbSHeejin Ahn           BuildMI(*MBB, *RangeBegin, RangeBegin->getDebugLoc(),
1103*c4ac74fbSHeejin Ahn                   TII.get(WebAssembly::TRY))
1104*c4ac74fbSHeejin Ahn               .addImm(int64_t(WebAssembly::ExprType::Void));
1105*c4ac74fbSHeejin Ahn 
1106*c4ac74fbSHeejin Ahn       // Create the nested EH pad and fill instructions in.
1107*c4ac74fbSHeejin Ahn       MachineBasicBlock *NestedEHPad = MF.CreateMachineBasicBlock();
1108*c4ac74fbSHeejin Ahn       MF.insert(std::next(MBB->getIterator()), NestedEHPad);
1109*c4ac74fbSHeejin Ahn       NestedEHPad->setIsEHPad();
1110*c4ac74fbSHeejin Ahn       NestedEHPad->setIsEHScopeEntry();
1111*c4ac74fbSHeejin Ahn       BuildMI(NestedEHPad, RangeEnd->getDebugLoc(), TII.get(WebAssembly::CATCH),
1112*c4ac74fbSHeejin Ahn               ExnReg);
1113*c4ac74fbSHeejin Ahn       BuildMI(NestedEHPad, RangeEnd->getDebugLoc(), TII.get(WebAssembly::BR))
1114*c4ac74fbSHeejin Ahn           .addMBB(BrDest);
1115*c4ac74fbSHeejin Ahn 
1116*c4ac74fbSHeejin Ahn       // Create the nested continuation BB and end_try instruction.
1117*c4ac74fbSHeejin Ahn       MachineBasicBlock *NestedCont = MF.CreateMachineBasicBlock();
1118*c4ac74fbSHeejin Ahn       MF.insert(std::next(NestedEHPad->getIterator()), NestedCont);
1119*c4ac74fbSHeejin Ahn       MachineInstr *NestedEndTry =
1120*c4ac74fbSHeejin Ahn           BuildMI(*NestedCont, NestedCont->begin(), RangeEnd->getDebugLoc(),
1121*c4ac74fbSHeejin Ahn                   TII.get(WebAssembly::END_TRY));
1122*c4ac74fbSHeejin Ahn       // In case MBB has more instructions after the try range, move them to the
1123*c4ac74fbSHeejin Ahn       // new nested continuation BB.
1124*c4ac74fbSHeejin Ahn       NestedCont->splice(NestedCont->end(), MBB,
1125*c4ac74fbSHeejin Ahn                          std::next(RangeEnd->getIterator()), MBB->end());
1126*c4ac74fbSHeejin Ahn       registerTryScope(NestedTry, NestedEndTry, NestedEHPad);
1127*c4ac74fbSHeejin Ahn 
1128*c4ac74fbSHeejin Ahn       // Fix predecessor-successor relationship.
1129*c4ac74fbSHeejin Ahn       NestedCont->transferSuccessors(MBB);
1130*c4ac74fbSHeejin Ahn       if (EHPad)
1131*c4ac74fbSHeejin Ahn         NestedCont->removeSuccessor(EHPad);
1132*c4ac74fbSHeejin Ahn       MBB->addSuccessor(NestedEHPad);
1133*c4ac74fbSHeejin Ahn       MBB->addSuccessor(NestedCont);
1134*c4ac74fbSHeejin Ahn       NestedEHPad->addSuccessor(BrDest);
1135*c4ac74fbSHeejin Ahn     }
1136*c4ac74fbSHeejin Ahn   }
1137*c4ac74fbSHeejin Ahn 
1138*c4ac74fbSHeejin Ahn   // Renumber BBs and recalculate ScopeTop info because new BBs might have been
1139*c4ac74fbSHeejin Ahn   // created and inserted above.
1140*c4ac74fbSHeejin Ahn   MF.RenumberBlocks();
1141*c4ac74fbSHeejin Ahn   ScopeTops.clear();
1142*c4ac74fbSHeejin Ahn   ScopeTops.resize(MF.getNumBlockIDs());
1143*c4ac74fbSHeejin Ahn   for (auto &MBB : reverse(MF)) {
1144*c4ac74fbSHeejin Ahn     for (auto &MI : reverse(MBB)) {
1145*c4ac74fbSHeejin Ahn       if (ScopeTops[MBB.getNumber()])
1146*c4ac74fbSHeejin Ahn         break;
1147*c4ac74fbSHeejin Ahn       switch (MI.getOpcode()) {
1148*c4ac74fbSHeejin Ahn       case WebAssembly::END_BLOCK:
1149*c4ac74fbSHeejin Ahn       case WebAssembly::END_LOOP:
1150*c4ac74fbSHeejin Ahn       case WebAssembly::END_TRY:
1151*c4ac74fbSHeejin Ahn         ScopeTops[MBB.getNumber()] = EndToBegin[&MI]->getParent();
1152*c4ac74fbSHeejin Ahn         break;
1153*c4ac74fbSHeejin Ahn       case WebAssembly::CATCH:
1154*c4ac74fbSHeejin Ahn         ScopeTops[MBB.getNumber()] = EHPadToTry[&MBB]->getParent();
1155*c4ac74fbSHeejin Ahn         break;
1156*c4ac74fbSHeejin Ahn       }
1157*c4ac74fbSHeejin Ahn     }
1158*c4ac74fbSHeejin Ahn   }
1159*c4ac74fbSHeejin Ahn 
1160*c4ac74fbSHeejin Ahn   // Recompute the dominator tree.
1161*c4ac74fbSHeejin Ahn   getAnalysis<MachineDominatorTree>().runOnMachineFunction(MF);
1162*c4ac74fbSHeejin Ahn 
1163*c4ac74fbSHeejin Ahn   // Place block markers for newly added branches.
1164*c4ac74fbSHeejin Ahn   SmallVector <MachineBasicBlock *, 8> BrDests;
1165*c4ac74fbSHeejin Ahn   for (auto &P : BrDestToTryRanges)
1166*c4ac74fbSHeejin Ahn     BrDests.push_back(P.first);
1167*c4ac74fbSHeejin Ahn   llvm::sort(BrDests,
1168*c4ac74fbSHeejin Ahn              [&](const MachineBasicBlock *A, const MachineBasicBlock *B) {
1169*c4ac74fbSHeejin Ahn                auto ANum = A->getNumber();
1170*c4ac74fbSHeejin Ahn                auto BNum = B->getNumber();
1171*c4ac74fbSHeejin Ahn                return ANum < BNum;
1172*c4ac74fbSHeejin Ahn              });
1173*c4ac74fbSHeejin Ahn   for (auto *Dest : BrDests)
1174*c4ac74fbSHeejin Ahn     placeBlockMarker(*Dest);
1175*c4ac74fbSHeejin Ahn 
1176*c4ac74fbSHeejin Ahn   return true;
1177*c4ac74fbSHeejin Ahn }
1178*c4ac74fbSHeejin Ahn 
11791d68e80fSDan Gohman static unsigned
118018c56a07SHeejin Ahn getDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
11811d68e80fSDan Gohman          const MachineBasicBlock *MBB) {
11821d68e80fSDan Gohman   unsigned Depth = 0;
11831d68e80fSDan Gohman   for (auto X : reverse(Stack)) {
11841d68e80fSDan Gohman     if (X == MBB)
11851d68e80fSDan Gohman       break;
11861d68e80fSDan Gohman     ++Depth;
11871d68e80fSDan Gohman   }
11881d68e80fSDan Gohman   assert(Depth < Stack.size() && "Branch destination should be in scope");
11891d68e80fSDan Gohman   return Depth;
11901d68e80fSDan Gohman }
11911d68e80fSDan Gohman 
11922726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable,
11932726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar,
11942726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of
11952726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks
11962726b88cSDan Gohman /// that end at the function end need to have a return type signature that
11972726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function
11982726b88cSDan Gohman /// checks for such cases and fixes up the signatures.
1199e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) {
1200e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
12012726b88cSDan Gohman   assert(MFI.getResults().size() <= 1);
12022726b88cSDan Gohman 
12032726b88cSDan Gohman   if (MFI.getResults().empty())
12042726b88cSDan Gohman     return;
12052726b88cSDan Gohman 
120618c56a07SHeejin Ahn   WebAssembly::ExprType RetType;
12072726b88cSDan Gohman   switch (MFI.getResults().front().SimpleTy) {
1208f208f631SHeejin Ahn   case MVT::i32:
120918c56a07SHeejin Ahn     RetType = WebAssembly::ExprType::I32;
1210f208f631SHeejin Ahn     break;
1211f208f631SHeejin Ahn   case MVT::i64:
121218c56a07SHeejin Ahn     RetType = WebAssembly::ExprType::I64;
1213f208f631SHeejin Ahn     break;
1214f208f631SHeejin Ahn   case MVT::f32:
121518c56a07SHeejin Ahn     RetType = WebAssembly::ExprType::F32;
1216f208f631SHeejin Ahn     break;
1217f208f631SHeejin Ahn   case MVT::f64:
121818c56a07SHeejin Ahn     RetType = WebAssembly::ExprType::F64;
1219f208f631SHeejin Ahn     break;
12202c783859SDerek Schuff   case MVT::v16i8:
12212c783859SDerek Schuff   case MVT::v8i16:
12222c783859SDerek Schuff   case MVT::v4i32:
122351ed131eSDerek Schuff   case MVT::v2i64:
12242c783859SDerek Schuff   case MVT::v4f32:
122551ed131eSDerek Schuff   case MVT::v2f64:
122618c56a07SHeejin Ahn     RetType = WebAssembly::ExprType::V128;
12272c783859SDerek Schuff     break;
1228f208f631SHeejin Ahn   case MVT::ExceptRef:
122918c56a07SHeejin Ahn     RetType = WebAssembly::ExprType::ExceptRef;
1230f208f631SHeejin Ahn     break;
1231f208f631SHeejin Ahn   default:
1232f208f631SHeejin Ahn     llvm_unreachable("unexpected return type");
12332726b88cSDan Gohman   }
12342726b88cSDan Gohman 
12352726b88cSDan Gohman   for (MachineBasicBlock &MBB : reverse(MF)) {
12362726b88cSDan Gohman     for (MachineInstr &MI : reverse(MBB)) {
1237801bf7ebSShiva Chen       if (MI.isPosition() || MI.isDebugInstr())
12382726b88cSDan Gohman         continue;
12392726b88cSDan Gohman       if (MI.getOpcode() == WebAssembly::END_BLOCK) {
124018c56a07SHeejin Ahn         EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
12412726b88cSDan Gohman         continue;
12422726b88cSDan Gohman       }
12432726b88cSDan Gohman       if (MI.getOpcode() == WebAssembly::END_LOOP) {
124418c56a07SHeejin Ahn         EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
12452726b88cSDan Gohman         continue;
12462726b88cSDan Gohman       }
12472726b88cSDan Gohman       // Something other than an `end`. We're done.
12482726b88cSDan Gohman       return;
12492726b88cSDan Gohman     }
12502726b88cSDan Gohman   }
12512726b88cSDan Gohman }
12522726b88cSDan Gohman 
1253d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body
1254d934cb88SDan Gohman // were a block.
125518c56a07SHeejin Ahn static void appendEndToFunction(MachineFunction &MF,
1256d934cb88SDan Gohman                                 const WebAssemblyInstrInfo &TII) {
125710b31358SDerek Schuff   BuildMI(MF.back(), MF.back().end(),
125810b31358SDerek Schuff           MF.back().findPrevDebugLoc(MF.back().end()),
1259d934cb88SDan Gohman           TII.get(WebAssembly::END_FUNCTION));
1260d934cb88SDan Gohman }
1261d934cb88SDan Gohman 
1262e76fa9ecSHeejin Ahn /// Insert LOOP/TRY/BLOCK markers at appropriate places.
1263e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) {
1264e76fa9ecSHeejin Ahn   // We allocate one more than the number of blocks in the function to
1265e76fa9ecSHeejin Ahn   // accommodate for the possible fake block we may insert at the end.
1266e76fa9ecSHeejin Ahn   ScopeTops.resize(MF.getNumBlockIDs() + 1);
12678fe7e86bSDan Gohman   // Place the LOOP for MBB if MBB is the header of a loop.
1268e76fa9ecSHeejin Ahn   for (auto &MBB : MF)
1269e76fa9ecSHeejin Ahn     placeLoopMarker(MBB);
127044a5a4b1SHeejin Ahn 
1271d6f48786SHeejin Ahn   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
127244a5a4b1SHeejin Ahn   for (auto &MBB : MF) {
127344a5a4b1SHeejin Ahn     if (MBB.isEHPad()) {
127444a5a4b1SHeejin Ahn       // Place the TRY for MBB if MBB is the EH pad of an exception.
1275e76fa9ecSHeejin Ahn       if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1276e76fa9ecSHeejin Ahn           MF.getFunction().hasPersonalityFn())
1277e76fa9ecSHeejin Ahn         placeTryMarker(MBB);
127844a5a4b1SHeejin Ahn     } else {
127932807932SDan Gohman       // Place the BLOCK for MBB if MBB is branched to from above.
1280e76fa9ecSHeejin Ahn       placeBlockMarker(MBB);
1281950a13cfSDan Gohman     }
128244a5a4b1SHeejin Ahn   }
1283*c4ac74fbSHeejin Ahn   // Fix mismatches in unwind destinations induced by linearizing the code.
1284*c4ac74fbSHeejin Ahn   fixUnwindMismatches(MF);
128544a5a4b1SHeejin Ahn }
1286950a13cfSDan Gohman 
1287e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) {
12881d68e80fSDan Gohman   // Now rewrite references to basic blocks to be depth immediates.
12891d68e80fSDan Gohman   SmallVector<const MachineBasicBlock *, 8> Stack;
12901d68e80fSDan Gohman   for (auto &MBB : reverse(MF)) {
1291e76fa9ecSHeejin Ahn     for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) {
1292e76fa9ecSHeejin Ahn       MachineInstr &MI = *I;
12931d68e80fSDan Gohman       switch (MI.getOpcode()) {
12941d68e80fSDan Gohman       case WebAssembly::BLOCK:
1295e76fa9ecSHeejin Ahn       case WebAssembly::TRY:
1296e76fa9ecSHeejin Ahn         assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <=
1297e76fa9ecSHeejin Ahn                    MBB.getNumber() &&
1298e76fa9ecSHeejin Ahn                "Block/try marker should be balanced");
1299e76fa9ecSHeejin Ahn         Stack.pop_back();
1300e76fa9ecSHeejin Ahn         break;
1301e76fa9ecSHeejin Ahn 
13021d68e80fSDan Gohman       case WebAssembly::LOOP:
13031d68e80fSDan Gohman         assert(Stack.back() == &MBB && "Loop top should be balanced");
13041d68e80fSDan Gohman         Stack.pop_back();
13051d68e80fSDan Gohman         break;
1306e76fa9ecSHeejin Ahn 
13071d68e80fSDan Gohman       case WebAssembly::END_BLOCK:
1308e76fa9ecSHeejin Ahn       case WebAssembly::END_TRY:
13091d68e80fSDan Gohman         Stack.push_back(&MBB);
13101d68e80fSDan Gohman         break;
1311e76fa9ecSHeejin Ahn 
13121d68e80fSDan Gohman       case WebAssembly::END_LOOP:
1313e76fa9ecSHeejin Ahn         Stack.push_back(EndToBegin[&MI]->getParent());
13141d68e80fSDan Gohman         break;
1315e76fa9ecSHeejin Ahn 
13161d68e80fSDan Gohman       default:
13171d68e80fSDan Gohman         if (MI.isTerminator()) {
13181d68e80fSDan Gohman           // Rewrite MBB operands to be depth immediates.
13191d68e80fSDan Gohman           SmallVector<MachineOperand, 4> Ops(MI.operands());
13201d68e80fSDan Gohman           while (MI.getNumOperands() > 0)
13211d68e80fSDan Gohman             MI.RemoveOperand(MI.getNumOperands() - 1);
13221d68e80fSDan Gohman           for (auto MO : Ops) {
13231d68e80fSDan Gohman             if (MO.isMBB())
132418c56a07SHeejin Ahn               MO = MachineOperand::CreateImm(getDepth(Stack, MO.getMBB()));
13251d68e80fSDan Gohman             MI.addOperand(MF, MO);
132632807932SDan Gohman           }
13271d68e80fSDan Gohman         }
13281d68e80fSDan Gohman         break;
13291d68e80fSDan Gohman       }
13301d68e80fSDan Gohman     }
13311d68e80fSDan Gohman   }
13321d68e80fSDan Gohman   assert(Stack.empty() && "Control flow should be balanced");
1333e76fa9ecSHeejin Ahn }
13342726b88cSDan Gohman 
1335e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::releaseMemory() {
1336e76fa9ecSHeejin Ahn   ScopeTops.clear();
1337e76fa9ecSHeejin Ahn   BeginToEnd.clear();
1338e76fa9ecSHeejin Ahn   EndToBegin.clear();
1339e76fa9ecSHeejin Ahn   TryToEHPad.clear();
1340e76fa9ecSHeejin Ahn   EHPadToTry.clear();
1341*c4ac74fbSHeejin Ahn   AppendixBB = nullptr;
13421d68e80fSDan Gohman }
134332807932SDan Gohman 
1344950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
1345d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n"
1346950a13cfSDan Gohman                        "********** Function: "
1347950a13cfSDan Gohman                     << MF.getName() << '\n');
1348cf699b45SHeejin Ahn   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
1349950a13cfSDan Gohman 
1350e76fa9ecSHeejin Ahn   releaseMemory();
1351e76fa9ecSHeejin Ahn 
1352e040533eSDan Gohman   // Liveness is not tracked for VALUE_STACK physreg.
13539c3bf318SDerek Schuff   MF.getRegInfo().invalidateLiveness();
1354950a13cfSDan Gohman 
1355e76fa9ecSHeejin Ahn   // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes.
1356e76fa9ecSHeejin Ahn   placeMarkers(MF);
1357e76fa9ecSHeejin Ahn 
1358*c4ac74fbSHeejin Ahn   // Remove unnecessary instructions possibly introduced by try/end_trys.
1359cf699b45SHeejin Ahn   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1360cf699b45SHeejin Ahn       MF.getFunction().hasPersonalityFn())
1361cf699b45SHeejin Ahn     removeUnnecessaryInstrs(MF);
1362cf699b45SHeejin Ahn 
1363e76fa9ecSHeejin Ahn   // Convert MBB operands in terminators to relative depth immediates.
1364e76fa9ecSHeejin Ahn   rewriteDepthImmediates(MF);
1365e76fa9ecSHeejin Ahn 
1366e76fa9ecSHeejin Ahn   // Fix up block/loop/try signatures at the end of the function to conform to
1367e76fa9ecSHeejin Ahn   // WebAssembly's rules.
1368e76fa9ecSHeejin Ahn   fixEndsAtEndOfFunction(MF);
1369e76fa9ecSHeejin Ahn 
1370e76fa9ecSHeejin Ahn   // Add an end instruction at the end of the function body.
1371e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1372e76fa9ecSHeejin Ahn   if (!MF.getSubtarget<WebAssemblySubtarget>()
1373e76fa9ecSHeejin Ahn            .getTargetTriple()
1374e76fa9ecSHeejin Ahn            .isOSBinFormatELF())
137518c56a07SHeejin Ahn     appendEndToFunction(MF, TII);
137632807932SDan Gohman 
13771aaa481fSHeejin Ahn   MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified();
1378950a13cfSDan Gohman   return true;
1379950a13cfSDan Gohman }
1380