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"
27276f9e8cSHeejin Ahn #include "WebAssemblySortRegion.h"
28950a13cfSDan Gohman #include "WebAssemblySubtarget.h"
294fc4e42dSDan Gohman #include "WebAssemblyUtilities.h"
30c4ac74fbSHeejin Ahn #include "llvm/ADT/Statistic.h"
3132807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h"
32950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
33904cd3e0SReid Kleckner #include "llvm/CodeGen/MachineLoopInfo.h"
34e76fa9ecSHeejin Ahn #include "llvm/MC/MCAsmInfo.h"
35fe0006c8SSimon Pilgrim #include "llvm/Target/TargetMachine.h"
36950a13cfSDan Gohman using namespace llvm;
37276f9e8cSHeejin Ahn using WebAssembly::SortRegionInfo;
38950a13cfSDan Gohman 
39950a13cfSDan Gohman #define DEBUG_TYPE "wasm-cfg-stackify"
40950a13cfSDan Gohman 
41c4ac74fbSHeejin Ahn STATISTIC(NumUnwindMismatches, "Number of EH pad unwind mismatches found");
42c4ac74fbSHeejin Ahn 
43950a13cfSDan Gohman namespace {
44950a13cfSDan Gohman class WebAssemblyCFGStackify final : public MachineFunctionPass {
45117296c0SMehdi Amini   StringRef getPassName() const override { return "WebAssembly CFG Stackify"; }
46950a13cfSDan Gohman 
47950a13cfSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
4832807932SDan Gohman     AU.addRequired<MachineDominatorTree>();
49950a13cfSDan Gohman     AU.addRequired<MachineLoopInfo>();
50e76fa9ecSHeejin Ahn     AU.addRequired<WebAssemblyExceptionInfo>();
51950a13cfSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
52950a13cfSDan Gohman   }
53950a13cfSDan Gohman 
54950a13cfSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
55950a13cfSDan Gohman 
56e76fa9ecSHeejin Ahn   // For each block whose label represents the end of a scope, record the block
57e76fa9ecSHeejin Ahn   // which holds the beginning of the scope. This will allow us to quickly skip
58e76fa9ecSHeejin Ahn   // over scoped regions when walking blocks.
59e76fa9ecSHeejin Ahn   SmallVector<MachineBasicBlock *, 8> ScopeTops;
60*1cc52357SHeejin Ahn   void updateScopeTops(MachineBasicBlock *Begin, MachineBasicBlock *End) {
61*1cc52357SHeejin Ahn     int EndNo = End->getNumber();
62*1cc52357SHeejin Ahn     if (!ScopeTops[EndNo] || ScopeTops[EndNo]->getNumber() > Begin->getNumber())
63*1cc52357SHeejin Ahn       ScopeTops[EndNo] = Begin;
64*1cc52357SHeejin Ahn   }
65e76fa9ecSHeejin Ahn 
66c4ac74fbSHeejin Ahn   // Placing markers.
67e76fa9ecSHeejin Ahn   void placeMarkers(MachineFunction &MF);
68e76fa9ecSHeejin Ahn   void placeBlockMarker(MachineBasicBlock &MBB);
69e76fa9ecSHeejin Ahn   void placeLoopMarker(MachineBasicBlock &MBB);
70e76fa9ecSHeejin Ahn   void placeTryMarker(MachineBasicBlock &MBB);
71cf699b45SHeejin Ahn   void removeUnnecessaryInstrs(MachineFunction &MF);
72c4ac74fbSHeejin Ahn   bool fixUnwindMismatches(MachineFunction &MF);
73e76fa9ecSHeejin Ahn   void rewriteDepthImmediates(MachineFunction &MF);
74e76fa9ecSHeejin Ahn   void fixEndsAtEndOfFunction(MachineFunction &MF);
75e76fa9ecSHeejin Ahn 
76e76fa9ecSHeejin Ahn   // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY).
77e76fa9ecSHeejin Ahn   DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd;
78e76fa9ecSHeejin Ahn   // For each END_(BLOCK|LOOP|TRY), the corresponding BLOCK|LOOP|TRY.
79e76fa9ecSHeejin Ahn   DenseMap<const MachineInstr *, MachineInstr *> EndToBegin;
80e76fa9ecSHeejin Ahn   // <TRY marker, EH pad> map
81e76fa9ecSHeejin Ahn   DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad;
82e76fa9ecSHeejin Ahn   // <EH pad, TRY marker> map
83e76fa9ecSHeejin Ahn   DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry;
84e76fa9ecSHeejin Ahn 
85c4ac74fbSHeejin Ahn   // There can be an appendix block at the end of each function, shared for:
86c4ac74fbSHeejin Ahn   // - creating a correct signature for fallthrough returns
87c4ac74fbSHeejin Ahn   // - target for rethrows that need to unwind to the caller, but are trapped
88c4ac74fbSHeejin Ahn   //   inside another try/catch
89c4ac74fbSHeejin Ahn   MachineBasicBlock *AppendixBB = nullptr;
90c4ac74fbSHeejin Ahn   MachineBasicBlock *getAppendixBlock(MachineFunction &MF) {
91c4ac74fbSHeejin Ahn     if (!AppendixBB) {
92c4ac74fbSHeejin Ahn       AppendixBB = MF.CreateMachineBasicBlock();
93c4ac74fbSHeejin Ahn       // Give it a fake predecessor so that AsmPrinter prints its label.
94c4ac74fbSHeejin Ahn       AppendixBB->addSuccessor(AppendixBB);
95c4ac74fbSHeejin Ahn       MF.push_back(AppendixBB);
96c4ac74fbSHeejin Ahn     }
97c4ac74fbSHeejin Ahn     return AppendixBB;
98c4ac74fbSHeejin Ahn   }
99c4ac74fbSHeejin Ahn 
100cf699b45SHeejin Ahn   // Helper functions to register / unregister scope information created by
101cf699b45SHeejin Ahn   // marker instructions.
102e76fa9ecSHeejin Ahn   void registerScope(MachineInstr *Begin, MachineInstr *End);
103e76fa9ecSHeejin Ahn   void registerTryScope(MachineInstr *Begin, MachineInstr *End,
104e76fa9ecSHeejin Ahn                         MachineBasicBlock *EHPad);
105cf699b45SHeejin Ahn   void unregisterScope(MachineInstr *Begin);
106e76fa9ecSHeejin Ahn 
107950a13cfSDan Gohman public:
108950a13cfSDan Gohman   static char ID; // Pass identification, replacement for typeid
109950a13cfSDan Gohman   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
110e76fa9ecSHeejin Ahn   ~WebAssemblyCFGStackify() override { releaseMemory(); }
111e76fa9ecSHeejin Ahn   void releaseMemory() override;
112950a13cfSDan Gohman };
113950a13cfSDan Gohman } // end anonymous namespace
114950a13cfSDan Gohman 
115950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0;
11640926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE,
117c4ac74fbSHeejin Ahn                 "Insert BLOCK/LOOP/TRY markers for WebAssembly scopes", false,
118f208f631SHeejin Ahn                 false)
11940926451SJacob Gravelle 
120950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() {
121950a13cfSDan Gohman   return new WebAssemblyCFGStackify();
122950a13cfSDan Gohman }
123950a13cfSDan Gohman 
124b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as
125b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized
126b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough
127b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any
128b3aa1ecaSDan Gohman /// explicit mentions.
12918c56a07SHeejin Ahn static bool explicitlyBranchesTo(MachineBasicBlock *Pred,
13035e4a289SDan Gohman                                  MachineBasicBlock *MBB) {
131b3aa1ecaSDan Gohman   for (MachineInstr &MI : Pred->terminators())
132b3aa1ecaSDan Gohman     for (MachineOperand &MO : MI.explicit_operands())
133b3aa1ecaSDan Gohman       if (MO.isMBB() && MO.getMBB() == MBB)
134b3aa1ecaSDan Gohman         return true;
135b3aa1ecaSDan Gohman   return false;
136b3aa1ecaSDan Gohman }
137b3aa1ecaSDan Gohman 
138e76fa9ecSHeejin Ahn // Returns an iterator to the earliest position possible within the MBB,
139e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
140e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains
141e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, AfterSet is only
142e76fa9ecSHeejin Ahn // used for sanity checking.
143*1cc52357SHeejin Ahn template <typename Container>
144e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator
145*1cc52357SHeejin Ahn getEarliestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet,
146*1cc52357SHeejin Ahn                      const Container &AfterSet) {
147e76fa9ecSHeejin Ahn   auto InsertPos = MBB->end();
148e76fa9ecSHeejin Ahn   while (InsertPos != MBB->begin()) {
149e76fa9ecSHeejin Ahn     if (BeforeSet.count(&*std::prev(InsertPos))) {
150e76fa9ecSHeejin Ahn #ifndef NDEBUG
151e76fa9ecSHeejin Ahn       // Sanity check
152e76fa9ecSHeejin Ahn       for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos)
153e76fa9ecSHeejin Ahn         assert(!AfterSet.count(&*std::prev(Pos)));
154e76fa9ecSHeejin Ahn #endif
155e76fa9ecSHeejin Ahn       break;
156e76fa9ecSHeejin Ahn     }
157e76fa9ecSHeejin Ahn     --InsertPos;
158e76fa9ecSHeejin Ahn   }
159e76fa9ecSHeejin Ahn   return InsertPos;
160e76fa9ecSHeejin Ahn }
161e76fa9ecSHeejin Ahn 
162e76fa9ecSHeejin Ahn // Returns an iterator to the latest position possible within the MBB,
163e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
164e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains
165e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, BeforeSet is only
166e76fa9ecSHeejin Ahn // used for sanity checking.
167*1cc52357SHeejin Ahn template <typename Container>
168e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator
169*1cc52357SHeejin Ahn getLatestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet,
170*1cc52357SHeejin Ahn                    const Container &AfterSet) {
171e76fa9ecSHeejin Ahn   auto InsertPos = MBB->begin();
172e76fa9ecSHeejin Ahn   while (InsertPos != MBB->end()) {
173e76fa9ecSHeejin Ahn     if (AfterSet.count(&*InsertPos)) {
174e76fa9ecSHeejin Ahn #ifndef NDEBUG
175e76fa9ecSHeejin Ahn       // Sanity check
176e76fa9ecSHeejin Ahn       for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos)
177e76fa9ecSHeejin Ahn         assert(!BeforeSet.count(&*Pos));
178e76fa9ecSHeejin Ahn #endif
179e76fa9ecSHeejin Ahn       break;
180e76fa9ecSHeejin Ahn     }
181e76fa9ecSHeejin Ahn     ++InsertPos;
182e76fa9ecSHeejin Ahn   }
183e76fa9ecSHeejin Ahn   return InsertPos;
184e76fa9ecSHeejin Ahn }
185e76fa9ecSHeejin Ahn 
186e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin,
187e76fa9ecSHeejin Ahn                                            MachineInstr *End) {
188e76fa9ecSHeejin Ahn   BeginToEnd[Begin] = End;
189e76fa9ecSHeejin Ahn   EndToBegin[End] = Begin;
190e76fa9ecSHeejin Ahn }
191e76fa9ecSHeejin Ahn 
192e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin,
193e76fa9ecSHeejin Ahn                                               MachineInstr *End,
194e76fa9ecSHeejin Ahn                                               MachineBasicBlock *EHPad) {
195e76fa9ecSHeejin Ahn   registerScope(Begin, End);
196e76fa9ecSHeejin Ahn   TryToEHPad[Begin] = EHPad;
197e76fa9ecSHeejin Ahn   EHPadToTry[EHPad] = Begin;
198e76fa9ecSHeejin Ahn }
199e76fa9ecSHeejin Ahn 
200cf699b45SHeejin Ahn void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) {
201cf699b45SHeejin Ahn   assert(BeginToEnd.count(Begin));
202cf699b45SHeejin Ahn   MachineInstr *End = BeginToEnd[Begin];
203cf699b45SHeejin Ahn   assert(EndToBegin.count(End));
204cf699b45SHeejin Ahn   BeginToEnd.erase(Begin);
205cf699b45SHeejin Ahn   EndToBegin.erase(End);
206cf699b45SHeejin Ahn   MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin);
207cf699b45SHeejin Ahn   if (EHPad) {
208cf699b45SHeejin Ahn     assert(EHPadToTry.count(EHPad));
209cf699b45SHeejin Ahn     TryToEHPad.erase(Begin);
210cf699b45SHeejin Ahn     EHPadToTry.erase(EHPad);
211cf699b45SHeejin Ahn   }
212cf699b45SHeejin Ahn }
213cf699b45SHeejin Ahn 
21432807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed).
215c4ac74fbSHeejin Ahn // TODO Consider a more generalized way of handling block (and also loop and
216c4ac74fbSHeejin Ahn // try) signatures when we implement the multi-value proposal later.
217e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) {
21844a5a4b1SHeejin Ahn   assert(!MBB.isEHPad());
219e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
220e76fa9ecSHeejin Ahn   auto &MDT = getAnalysis<MachineDominatorTree>();
221e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
222e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
223e76fa9ecSHeejin Ahn 
2248fe7e86bSDan Gohman   // First compute the nearest common dominator of all forward non-fallthrough
2258fe7e86bSDan Gohman   // predecessors so that we minimize the time that the BLOCK is on the stack,
2268fe7e86bSDan Gohman   // which reduces overall stack height.
22732807932SDan Gohman   MachineBasicBlock *Header = nullptr;
22832807932SDan Gohman   bool IsBranchedTo = false;
22932807932SDan Gohman   int MBBNumber = MBB.getNumber();
230e76fa9ecSHeejin Ahn   for (MachineBasicBlock *Pred : MBB.predecessors()) {
23132807932SDan Gohman     if (Pred->getNumber() < MBBNumber) {
23232807932SDan Gohman       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
23352e240a0SHeejin Ahn       if (explicitlyBranchesTo(Pred, &MBB))
23432807932SDan Gohman         IsBranchedTo = true;
23532807932SDan Gohman     }
236e76fa9ecSHeejin Ahn   }
23732807932SDan Gohman   if (!Header)
23832807932SDan Gohman     return;
23932807932SDan Gohman   if (!IsBranchedTo)
24032807932SDan Gohman     return;
24132807932SDan Gohman 
2428fe7e86bSDan Gohman   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
2435c644c9bSHeejin Ahn   MachineBasicBlock *LayoutPred = MBB.getPrevNode();
2448fe7e86bSDan Gohman 
2458fe7e86bSDan Gohman   // If the nearest common dominator is inside a more deeply nested context,
2468fe7e86bSDan Gohman   // walk out to the nearest scope which isn't more deeply nested.
2478fe7e86bSDan Gohman   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
2488fe7e86bSDan Gohman     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
2498fe7e86bSDan Gohman       if (ScopeTop->getNumber() > Header->getNumber()) {
2508fe7e86bSDan Gohman         // Skip over an intervening scope.
2515c644c9bSHeejin Ahn         I = std::next(ScopeTop->getIterator());
2528fe7e86bSDan Gohman       } else {
2538fe7e86bSDan Gohman         // We found a scope level at an appropriate depth.
2548fe7e86bSDan Gohman         Header = ScopeTop;
2558fe7e86bSDan Gohman         break;
2568fe7e86bSDan Gohman       }
2578fe7e86bSDan Gohman     }
2588fe7e86bSDan Gohman   }
2598fe7e86bSDan Gohman 
2608fe7e86bSDan Gohman   // Decide where in Header to put the BLOCK.
261e76fa9ecSHeejin Ahn 
262e76fa9ecSHeejin Ahn   // Instructions that should go before the BLOCK.
263e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
264e76fa9ecSHeejin Ahn   // Instructions that should go after the BLOCK.
265e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
266e76fa9ecSHeejin Ahn   for (const auto &MI : *Header) {
26744a5a4b1SHeejin Ahn     // If there is a previously placed LOOP marker and the bottom block of the
26844a5a4b1SHeejin Ahn     // loop is above MBB, it should be after the BLOCK, because the loop is
26944a5a4b1SHeejin Ahn     // nested in this BLOCK. Otherwise it should be before the BLOCK.
27044a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP) {
27144a5a4b1SHeejin Ahn       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
27244a5a4b1SHeejin Ahn       if (MBB.getNumber() > LoopBottom->getNumber())
273e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
274e76fa9ecSHeejin Ahn #ifndef NDEBUG
275e76fa9ecSHeejin Ahn       else
276e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
277e76fa9ecSHeejin Ahn #endif
278e76fa9ecSHeejin Ahn     }
279e76fa9ecSHeejin Ahn 
280834debffSHeejin Ahn     // If there is a previously placed BLOCK/TRY marker and its corresponding
281834debffSHeejin Ahn     // END marker is before the current BLOCK's END marker, that should be
282834debffSHeejin Ahn     // placed after this BLOCK. Otherwise it should be placed before this BLOCK
283834debffSHeejin Ahn     // marker.
28444a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::BLOCK ||
285834debffSHeejin Ahn         MI.getOpcode() == WebAssembly::TRY) {
286834debffSHeejin Ahn       if (BeginToEnd[&MI]->getParent()->getNumber() <= MBB.getNumber())
287e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
288834debffSHeejin Ahn #ifndef NDEBUG
289834debffSHeejin Ahn       else
290834debffSHeejin Ahn         BeforeSet.insert(&MI);
291834debffSHeejin Ahn #endif
292834debffSHeejin Ahn     }
293e76fa9ecSHeejin Ahn 
294e76fa9ecSHeejin Ahn #ifndef NDEBUG
295e76fa9ecSHeejin Ahn     // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK.
296e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
297e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_LOOP ||
298e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY)
299e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
300e76fa9ecSHeejin Ahn #endif
301e76fa9ecSHeejin Ahn 
302e76fa9ecSHeejin Ahn     // Terminators should go after the BLOCK.
303e76fa9ecSHeejin Ahn     if (MI.isTerminator())
304e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
305e76fa9ecSHeejin Ahn   }
306e76fa9ecSHeejin Ahn 
307e76fa9ecSHeejin Ahn   // Local expression tree should go after the BLOCK.
308e76fa9ecSHeejin Ahn   for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
309e76fa9ecSHeejin Ahn        --I) {
310409b4391SYury Delendik     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
311409b4391SYury Delendik       continue;
312e76fa9ecSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
313e76fa9ecSHeejin Ahn       AfterSet.insert(&*std::prev(I));
314e76fa9ecSHeejin Ahn     else
315e76fa9ecSHeejin Ahn       break;
31632807932SDan Gohman   }
31732807932SDan Gohman 
3188fe7e86bSDan Gohman   // Add the BLOCK.
3192cb27072SThomas Lively   WebAssembly::BlockType ReturnType = WebAssembly::BlockType::Void;
32018c56a07SHeejin Ahn   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
32192401cc1SHeejin Ahn   MachineInstr *Begin =
32292401cc1SHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
3232726b88cSDan Gohman               TII.get(WebAssembly::BLOCK))
324d6f48786SHeejin Ahn           .addImm(int64_t(ReturnType));
3251d68e80fSDan Gohman 
326e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_BLOCK.
327e76fa9ecSHeejin Ahn   BeforeSet.clear();
328e76fa9ecSHeejin Ahn   AfterSet.clear();
329e76fa9ecSHeejin Ahn   for (auto &MI : MBB) {
330e76fa9ecSHeejin Ahn #ifndef NDEBUG
331e76fa9ecSHeejin Ahn     // END_BLOCK should precede existing LOOP and TRY markers.
332e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP ||
333e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::TRY)
334e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
335e76fa9ecSHeejin Ahn #endif
336e76fa9ecSHeejin Ahn 
337e76fa9ecSHeejin Ahn     // If there is a previously placed END_LOOP marker and the header of the
338e76fa9ecSHeejin Ahn     // loop is above this block's header, the END_LOOP should be placed after
339e76fa9ecSHeejin Ahn     // the BLOCK, because the loop contains this block. Otherwise the END_LOOP
340e76fa9ecSHeejin Ahn     // should be placed before the BLOCK. The same for END_TRY.
341e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP ||
342e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY) {
343e76fa9ecSHeejin Ahn       if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
344e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
345e76fa9ecSHeejin Ahn #ifndef NDEBUG
346e76fa9ecSHeejin Ahn       else
347e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
348e76fa9ecSHeejin Ahn #endif
349e76fa9ecSHeejin Ahn     }
350e76fa9ecSHeejin Ahn   }
351e76fa9ecSHeejin Ahn 
3521d68e80fSDan Gohman   // Mark the end of the block.
35318c56a07SHeejin Ahn   InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
35410b31358SDerek Schuff   MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
3552726b88cSDan Gohman                               TII.get(WebAssembly::END_BLOCK));
356e76fa9ecSHeejin Ahn   registerScope(Begin, End);
3578fe7e86bSDan Gohman 
3588fe7e86bSDan Gohman   // Track the farthest-spanning scope that ends at this point.
359*1cc52357SHeejin Ahn   updateScopeTops(Header, &MBB);
360950a13cfSDan Gohman }
361950a13cfSDan Gohman 
3628fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
363e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) {
364e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
365e76fa9ecSHeejin Ahn   const auto &MLI = getAnalysis<MachineLoopInfo>();
366276f9e8cSHeejin Ahn   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
367276f9e8cSHeejin Ahn   SortRegionInfo SRI(MLI, WEI);
368e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
369e76fa9ecSHeejin Ahn 
3708fe7e86bSDan Gohman   MachineLoop *Loop = MLI.getLoopFor(&MBB);
3718fe7e86bSDan Gohman   if (!Loop || Loop->getHeader() != &MBB)
3728fe7e86bSDan Gohman     return;
3738fe7e86bSDan Gohman 
3748fe7e86bSDan Gohman   // The operand of a LOOP is the first block after the loop. If the loop is the
3758fe7e86bSDan Gohman   // bottom of the function, insert a dummy block at the end.
376276f9e8cSHeejin Ahn   MachineBasicBlock *Bottom = SRI.getBottom(Loop);
3775c644c9bSHeejin Ahn   auto Iter = std::next(Bottom->getIterator());
378e3e4a5ffSDan Gohman   if (Iter == MF.end()) {
379c4ac74fbSHeejin Ahn     getAppendixBlock(MF);
3805c644c9bSHeejin Ahn     Iter = std::next(Bottom->getIterator());
381e3e4a5ffSDan Gohman   }
3828fe7e86bSDan Gohman   MachineBasicBlock *AfterLoop = &*Iter;
383f6857223SDan Gohman 
384e76fa9ecSHeejin Ahn   // Decide where in Header to put the LOOP.
385e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
386e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
387e76fa9ecSHeejin Ahn   for (const auto &MI : MBB) {
388e76fa9ecSHeejin Ahn     // LOOP marker should be after any existing loop that ends here. Otherwise
389e76fa9ecSHeejin Ahn     // we assume the instruction belongs to the loop.
390e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP)
391e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
392e76fa9ecSHeejin Ahn #ifndef NDEBUG
393e76fa9ecSHeejin Ahn     else
394e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
395e76fa9ecSHeejin Ahn #endif
396e76fa9ecSHeejin Ahn   }
397e76fa9ecSHeejin Ahn 
398e76fa9ecSHeejin Ahn   // Mark the beginning of the loop.
39918c56a07SHeejin Ahn   auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
40010b31358SDerek Schuff   MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos),
4012726b88cSDan Gohman                                 TII.get(WebAssembly::LOOP))
4022cb27072SThomas Lively                             .addImm(int64_t(WebAssembly::BlockType::Void));
4031d68e80fSDan Gohman 
404e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_LOOP.
405e76fa9ecSHeejin Ahn   BeforeSet.clear();
406e76fa9ecSHeejin Ahn   AfterSet.clear();
407e76fa9ecSHeejin Ahn #ifndef NDEBUG
408e76fa9ecSHeejin Ahn   for (const auto &MI : MBB)
409e76fa9ecSHeejin Ahn     // Existing END_LOOP markers belong to parent loops of this loop
410e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP)
411e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
412e76fa9ecSHeejin Ahn #endif
413e76fa9ecSHeejin Ahn 
414e76fa9ecSHeejin Ahn   // Mark the end of the loop (using arbitrary debug location that branched to
415e76fa9ecSHeejin Ahn   // the loop end as its location).
41618c56a07SHeejin Ahn   InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet);
41767f74aceSHeejin Ahn   DebugLoc EndDL = AfterLoop->pred_empty()
41867f74aceSHeejin Ahn                        ? DebugLoc()
41967f74aceSHeejin Ahn                        : (*AfterLoop->pred_rbegin())->findBranchDebugLoc();
420e76fa9ecSHeejin Ahn   MachineInstr *End =
421e76fa9ecSHeejin Ahn       BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP));
422e76fa9ecSHeejin Ahn   registerScope(Begin, End);
4238fe7e86bSDan Gohman 
4248fe7e86bSDan Gohman   assert((!ScopeTops[AfterLoop->getNumber()] ||
4258fe7e86bSDan Gohman           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
426442bfcecSDan Gohman          "With block sorting the outermost loop for a block should be first.");
427*1cc52357SHeejin Ahn   updateScopeTops(&MBB, AfterLoop);
428e3e4a5ffSDan Gohman }
429950a13cfSDan Gohman 
430e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) {
43144a5a4b1SHeejin Ahn   assert(MBB.isEHPad());
432e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
433e76fa9ecSHeejin Ahn   auto &MDT = getAnalysis<MachineDominatorTree>();
434e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
435276f9e8cSHeejin Ahn   const auto &MLI = getAnalysis<MachineLoopInfo>();
436e76fa9ecSHeejin Ahn   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
437276f9e8cSHeejin Ahn   SortRegionInfo SRI(MLI, WEI);
438e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
439e76fa9ecSHeejin Ahn 
440e76fa9ecSHeejin Ahn   // Compute the nearest common dominator of all unwind predecessors
441e76fa9ecSHeejin Ahn   MachineBasicBlock *Header = nullptr;
442e76fa9ecSHeejin Ahn   int MBBNumber = MBB.getNumber();
443e76fa9ecSHeejin Ahn   for (auto *Pred : MBB.predecessors()) {
444e76fa9ecSHeejin Ahn     if (Pred->getNumber() < MBBNumber) {
445e76fa9ecSHeejin Ahn       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
44618c56a07SHeejin Ahn       assert(!explicitlyBranchesTo(Pred, &MBB) &&
447e76fa9ecSHeejin Ahn              "Explicit branch to an EH pad!");
448e76fa9ecSHeejin Ahn     }
449e76fa9ecSHeejin Ahn   }
450e76fa9ecSHeejin Ahn   if (!Header)
451e76fa9ecSHeejin Ahn     return;
452e76fa9ecSHeejin Ahn 
453e76fa9ecSHeejin Ahn   // If this try is at the bottom of the function, insert a dummy block at the
454e76fa9ecSHeejin Ahn   // end.
455e76fa9ecSHeejin Ahn   WebAssemblyException *WE = WEI.getExceptionFor(&MBB);
456e76fa9ecSHeejin Ahn   assert(WE);
457276f9e8cSHeejin Ahn   MachineBasicBlock *Bottom = SRI.getBottom(WE);
458e76fa9ecSHeejin Ahn 
4595c644c9bSHeejin Ahn   auto Iter = std::next(Bottom->getIterator());
460e76fa9ecSHeejin Ahn   if (Iter == MF.end()) {
461c4ac74fbSHeejin Ahn     getAppendixBlock(MF);
4625c644c9bSHeejin Ahn     Iter = std::next(Bottom->getIterator());
463e76fa9ecSHeejin Ahn   }
46420cf0749SHeejin Ahn   MachineBasicBlock *Cont = &*Iter;
465e76fa9ecSHeejin Ahn 
46620cf0749SHeejin Ahn   assert(Cont != &MF.front());
4675c644c9bSHeejin Ahn   MachineBasicBlock *LayoutPred = Cont->getPrevNode();
468e76fa9ecSHeejin Ahn 
469e76fa9ecSHeejin Ahn   // If the nearest common dominator is inside a more deeply nested context,
470e76fa9ecSHeejin Ahn   // walk out to the nearest scope which isn't more deeply nested.
471e76fa9ecSHeejin Ahn   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
472e76fa9ecSHeejin Ahn     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
473e76fa9ecSHeejin Ahn       if (ScopeTop->getNumber() > Header->getNumber()) {
474e76fa9ecSHeejin Ahn         // Skip over an intervening scope.
4755c644c9bSHeejin Ahn         I = std::next(ScopeTop->getIterator());
476e76fa9ecSHeejin Ahn       } else {
477e76fa9ecSHeejin Ahn         // We found a scope level at an appropriate depth.
478e76fa9ecSHeejin Ahn         Header = ScopeTop;
479e76fa9ecSHeejin Ahn         break;
480e76fa9ecSHeejin Ahn       }
481e76fa9ecSHeejin Ahn     }
482e76fa9ecSHeejin Ahn   }
483e76fa9ecSHeejin Ahn 
484e76fa9ecSHeejin Ahn   // Decide where in Header to put the TRY.
485e76fa9ecSHeejin Ahn 
48644a5a4b1SHeejin Ahn   // Instructions that should go before the TRY.
487e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
48844a5a4b1SHeejin Ahn   // Instructions that should go after the TRY.
489e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
490e76fa9ecSHeejin Ahn   for (const auto &MI : *Header) {
49144a5a4b1SHeejin Ahn     // If there is a previously placed LOOP marker and the bottom block of the
49244a5a4b1SHeejin Ahn     // loop is above MBB, it should be after the TRY, because the loop is nested
49344a5a4b1SHeejin Ahn     // in this TRY. Otherwise it should be before the TRY.
494e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP) {
49544a5a4b1SHeejin Ahn       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
49644a5a4b1SHeejin Ahn       if (MBB.getNumber() > LoopBottom->getNumber())
497e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
498e76fa9ecSHeejin Ahn #ifndef NDEBUG
499e76fa9ecSHeejin Ahn       else
500e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
501e76fa9ecSHeejin Ahn #endif
502e76fa9ecSHeejin Ahn     }
503e76fa9ecSHeejin Ahn 
50444a5a4b1SHeejin Ahn     // All previously inserted BLOCK/TRY markers should be after the TRY because
50544a5a4b1SHeejin Ahn     // they are all nested trys.
50644a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::BLOCK ||
50744a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::TRY)
508e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
509e76fa9ecSHeejin Ahn 
510e76fa9ecSHeejin Ahn #ifndef NDEBUG
51144a5a4b1SHeejin Ahn     // All END_(BLOCK/LOOP/TRY) markers should be before the TRY.
51244a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
51344a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::END_LOOP ||
514e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY)
515e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
516e76fa9ecSHeejin Ahn #endif
517e76fa9ecSHeejin Ahn 
518e76fa9ecSHeejin Ahn     // Terminators should go after the TRY.
519e76fa9ecSHeejin Ahn     if (MI.isTerminator())
520e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
521e76fa9ecSHeejin Ahn   }
522e76fa9ecSHeejin Ahn 
5236a37c5d6SHeejin Ahn   // If Header unwinds to MBB (= Header contains 'invoke'), the try block should
5246a37c5d6SHeejin Ahn   // contain the call within it. So the call should go after the TRY. The
5256a37c5d6SHeejin Ahn   // exception is when the header's terminator is a rethrow instruction, in
5266a37c5d6SHeejin Ahn   // which case that instruction, not a call instruction before it, is gonna
5276a37c5d6SHeejin Ahn   // throw.
5286a37c5d6SHeejin Ahn   MachineInstr *ThrowingCall = nullptr;
5296a37c5d6SHeejin Ahn   if (MBB.isPredecessor(Header)) {
5306a37c5d6SHeejin Ahn     auto TermPos = Header->getFirstTerminator();
5316a37c5d6SHeejin Ahn     if (TermPos == Header->end() ||
5326a37c5d6SHeejin Ahn         TermPos->getOpcode() != WebAssembly::RETHROW) {
5336a37c5d6SHeejin Ahn       for (auto &MI : reverse(*Header)) {
5346a37c5d6SHeejin Ahn         if (MI.isCall()) {
5356a37c5d6SHeejin Ahn           AfterSet.insert(&MI);
5366a37c5d6SHeejin Ahn           ThrowingCall = &MI;
5376a37c5d6SHeejin Ahn           // Possibly throwing calls are usually wrapped by EH_LABEL
5386a37c5d6SHeejin Ahn           // instructions. We don't want to split them and the call.
5396a37c5d6SHeejin Ahn           if (MI.getIterator() != Header->begin() &&
5406a37c5d6SHeejin Ahn               std::prev(MI.getIterator())->isEHLabel()) {
5416a37c5d6SHeejin Ahn             AfterSet.insert(&*std::prev(MI.getIterator()));
5426a37c5d6SHeejin Ahn             ThrowingCall = &*std::prev(MI.getIterator());
5436a37c5d6SHeejin Ahn           }
5446a37c5d6SHeejin Ahn           break;
5456a37c5d6SHeejin Ahn         }
5466a37c5d6SHeejin Ahn       }
5476a37c5d6SHeejin Ahn     }
5486a37c5d6SHeejin Ahn   }
5496a37c5d6SHeejin Ahn 
550e76fa9ecSHeejin Ahn   // Local expression tree should go after the TRY.
5516a37c5d6SHeejin Ahn   // For BLOCK placement, we start the search from the previous instruction of a
5526a37c5d6SHeejin Ahn   // BB's terminator, but in TRY's case, we should start from the previous
5536a37c5d6SHeejin Ahn   // instruction of a call that can throw, or a EH_LABEL that precedes the call,
5546a37c5d6SHeejin Ahn   // because the return values of the call's previous instructions can be
5556a37c5d6SHeejin Ahn   // stackified and consumed by the throwing call.
5566a37c5d6SHeejin Ahn   auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall)
5576a37c5d6SHeejin Ahn                                     : Header->getFirstTerminator();
5586a37c5d6SHeejin Ahn   for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) {
559409b4391SYury Delendik     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
560409b4391SYury Delendik       continue;
561e76fa9ecSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
562e76fa9ecSHeejin Ahn       AfterSet.insert(&*std::prev(I));
563e76fa9ecSHeejin Ahn     else
564e76fa9ecSHeejin Ahn       break;
565e76fa9ecSHeejin Ahn   }
566e76fa9ecSHeejin Ahn 
567e76fa9ecSHeejin Ahn   // Add the TRY.
56818c56a07SHeejin Ahn   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
569e76fa9ecSHeejin Ahn   MachineInstr *Begin =
570e76fa9ecSHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
571e76fa9ecSHeejin Ahn               TII.get(WebAssembly::TRY))
5722cb27072SThomas Lively           .addImm(int64_t(WebAssembly::BlockType::Void));
573e76fa9ecSHeejin Ahn 
574e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_TRY.
575e76fa9ecSHeejin Ahn   BeforeSet.clear();
576e76fa9ecSHeejin Ahn   AfterSet.clear();
57720cf0749SHeejin Ahn   for (const auto &MI : *Cont) {
578e76fa9ecSHeejin Ahn #ifndef NDEBUG
57944a5a4b1SHeejin Ahn     // END_TRY should precede existing LOOP and BLOCK markers.
58044a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP ||
58144a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::BLOCK)
582e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
583e76fa9ecSHeejin Ahn 
584e76fa9ecSHeejin Ahn     // All END_TRY markers placed earlier belong to exceptions that contains
585e76fa9ecSHeejin Ahn     // this one.
586e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_TRY)
587e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
588e76fa9ecSHeejin Ahn #endif
589e76fa9ecSHeejin Ahn 
590e76fa9ecSHeejin Ahn     // If there is a previously placed END_LOOP marker and its header is after
591e76fa9ecSHeejin Ahn     // where TRY marker is, this loop is contained within the 'catch' part, so
592e76fa9ecSHeejin Ahn     // the END_TRY marker should go after that. Otherwise, the whole try-catch
593e76fa9ecSHeejin Ahn     // is contained within this loop, so the END_TRY should go before that.
594e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP) {
595222718fdSHeejin Ahn       // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they
596222718fdSHeejin Ahn       // are in the same BB, LOOP is always before TRY.
597222718fdSHeejin Ahn       if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber())
598e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
599e76fa9ecSHeejin Ahn #ifndef NDEBUG
600e76fa9ecSHeejin Ahn       else
601e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
602e76fa9ecSHeejin Ahn #endif
603e76fa9ecSHeejin Ahn     }
60444a5a4b1SHeejin Ahn 
60544a5a4b1SHeejin Ahn     // It is not possible for an END_BLOCK to be already in this block.
606e76fa9ecSHeejin Ahn   }
607e76fa9ecSHeejin Ahn 
608e76fa9ecSHeejin Ahn   // Mark the end of the TRY.
60920cf0749SHeejin Ahn   InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet);
610e76fa9ecSHeejin Ahn   MachineInstr *End =
61120cf0749SHeejin Ahn       BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(),
612e76fa9ecSHeejin Ahn               TII.get(WebAssembly::END_TRY));
613e76fa9ecSHeejin Ahn   registerTryScope(Begin, End, &MBB);
614e76fa9ecSHeejin Ahn 
61582da1ffcSHeejin Ahn   // Track the farthest-spanning scope that ends at this point. We create two
61682da1ffcSHeejin Ahn   // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB
61782da1ffcSHeejin Ahn   // with 'try'). We need to create 'catch' -> 'try' mapping here too because
61882da1ffcSHeejin Ahn   // markers should not span across 'catch'. For example, this should not
61982da1ffcSHeejin Ahn   // happen:
62082da1ffcSHeejin Ahn   //
62182da1ffcSHeejin Ahn   // try
62282da1ffcSHeejin Ahn   //   block     --|  (X)
62382da1ffcSHeejin Ahn   // catch         |
62482da1ffcSHeejin Ahn   //   end_block --|
62582da1ffcSHeejin Ahn   // end_try
626*1cc52357SHeejin Ahn   for (auto *End : {&MBB, Cont})
627*1cc52357SHeejin Ahn     updateScopeTops(Header, End);
62882da1ffcSHeejin Ahn }
629e76fa9ecSHeejin Ahn 
630cf699b45SHeejin Ahn void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) {
631cf699b45SHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
632cf699b45SHeejin Ahn 
633cf699b45SHeejin Ahn   // When there is an unconditional branch right before a catch instruction and
634cf699b45SHeejin Ahn   // it branches to the end of end_try marker, we don't need the branch, because
635cf699b45SHeejin Ahn   // it there is no exception, the control flow transfers to that point anyway.
636cf699b45SHeejin Ahn   // bb0:
637cf699b45SHeejin Ahn   //   try
638cf699b45SHeejin Ahn   //     ...
639cf699b45SHeejin Ahn   //     br bb2      <- Not necessary
640cf699b45SHeejin Ahn   // bb1:
641cf699b45SHeejin Ahn   //   catch
642cf699b45SHeejin Ahn   //     ...
643cf699b45SHeejin Ahn   // bb2:
644cf699b45SHeejin Ahn   //   end
645cf699b45SHeejin Ahn   for (auto &MBB : MF) {
646cf699b45SHeejin Ahn     if (!MBB.isEHPad())
647cf699b45SHeejin Ahn       continue;
648cf699b45SHeejin Ahn 
649cf699b45SHeejin Ahn     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
650cf699b45SHeejin Ahn     SmallVector<MachineOperand, 4> Cond;
6515c644c9bSHeejin Ahn     MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode();
652cf699b45SHeejin Ahn     MachineBasicBlock *Cont = BeginToEnd[EHPadToTry[&MBB]]->getParent();
653cf699b45SHeejin Ahn     bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond);
6543fe6ea46SHeejin Ahn     // This condition means either
6553fe6ea46SHeejin Ahn     // 1. This BB ends with a single unconditional branch whose destinaion is
6563fe6ea46SHeejin Ahn     //    Cont.
6573fe6ea46SHeejin Ahn     // 2. This BB ends with a conditional branch followed by an unconditional
6583fe6ea46SHeejin Ahn     //    branch, and the unconditional branch's destination is Cont.
6593fe6ea46SHeejin Ahn     // In both cases, we want to remove the last (= unconditional) branch.
660cf699b45SHeejin Ahn     if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) ||
6613fe6ea46SHeejin Ahn                        (!Cond.empty() && FBB && FBB == Cont))) {
6623fe6ea46SHeejin Ahn       bool ErasedUncondBr = false;
663a5099ad9SHeejin Ahn       (void)ErasedUncondBr;
6643fe6ea46SHeejin Ahn       for (auto I = EHPadLayoutPred->end(), E = EHPadLayoutPred->begin();
6653fe6ea46SHeejin Ahn            I != E; --I) {
6663fe6ea46SHeejin Ahn         auto PrevI = std::prev(I);
6673fe6ea46SHeejin Ahn         if (PrevI->isTerminator()) {
6683fe6ea46SHeejin Ahn           assert(PrevI->getOpcode() == WebAssembly::BR);
6693fe6ea46SHeejin Ahn           PrevI->eraseFromParent();
6703fe6ea46SHeejin Ahn           ErasedUncondBr = true;
6713fe6ea46SHeejin Ahn           break;
6723fe6ea46SHeejin Ahn         }
6733fe6ea46SHeejin Ahn       }
6743fe6ea46SHeejin Ahn       assert(ErasedUncondBr && "Unconditional branch not erased!");
6753fe6ea46SHeejin Ahn     }
676cf699b45SHeejin Ahn   }
677cf699b45SHeejin Ahn 
678cf699b45SHeejin Ahn   // When there are block / end_block markers that overlap with try / end_try
679cf699b45SHeejin Ahn   // markers, and the block and try markers' return types are the same, the
680cf699b45SHeejin Ahn   // block /end_block markers are not necessary, because try / end_try markers
681cf699b45SHeejin Ahn   // also can serve as boundaries for branches.
682cf699b45SHeejin Ahn   // block         <- Not necessary
683cf699b45SHeejin Ahn   //   try
684cf699b45SHeejin Ahn   //     ...
685cf699b45SHeejin Ahn   //   catch
686cf699b45SHeejin Ahn   //     ...
687cf699b45SHeejin Ahn   //   end
688cf699b45SHeejin Ahn   // end           <- Not necessary
689cf699b45SHeejin Ahn   SmallVector<MachineInstr *, 32> ToDelete;
690cf699b45SHeejin Ahn   for (auto &MBB : MF) {
691cf699b45SHeejin Ahn     for (auto &MI : MBB) {
692cf699b45SHeejin Ahn       if (MI.getOpcode() != WebAssembly::TRY)
693cf699b45SHeejin Ahn         continue;
694cf699b45SHeejin Ahn 
695cf699b45SHeejin Ahn       MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try];
696cf699b45SHeejin Ahn       MachineBasicBlock *TryBB = Try->getParent();
697cf699b45SHeejin Ahn       MachineBasicBlock *Cont = EndTry->getParent();
698cf699b45SHeejin Ahn       int64_t RetType = Try->getOperand(0).getImm();
6995c644c9bSHeejin Ahn       for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator());
700cf699b45SHeejin Ahn            B != TryBB->begin() && E != Cont->end() &&
701cf699b45SHeejin Ahn            std::prev(B)->getOpcode() == WebAssembly::BLOCK &&
702cf699b45SHeejin Ahn            E->getOpcode() == WebAssembly::END_BLOCK &&
703cf699b45SHeejin Ahn            std::prev(B)->getOperand(0).getImm() == RetType;
704cf699b45SHeejin Ahn            --B, ++E) {
705cf699b45SHeejin Ahn         ToDelete.push_back(&*std::prev(B));
706cf699b45SHeejin Ahn         ToDelete.push_back(&*E);
707cf699b45SHeejin Ahn       }
708cf699b45SHeejin Ahn     }
709cf699b45SHeejin Ahn   }
710cf699b45SHeejin Ahn   for (auto *MI : ToDelete) {
711cf699b45SHeejin Ahn     if (MI->getOpcode() == WebAssembly::BLOCK)
712cf699b45SHeejin Ahn       unregisterScope(MI);
713cf699b45SHeejin Ahn     MI->eraseFromParent();
714cf699b45SHeejin Ahn   }
715cf699b45SHeejin Ahn }
716cf699b45SHeejin Ahn 
71783c26eaeSHeejin Ahn // Get the appropriate copy opcode for the given register class.
71883c26eaeSHeejin Ahn static unsigned getCopyOpcode(const TargetRegisterClass *RC) {
71983c26eaeSHeejin Ahn   if (RC == &WebAssembly::I32RegClass)
72083c26eaeSHeejin Ahn     return WebAssembly::COPY_I32;
72183c26eaeSHeejin Ahn   if (RC == &WebAssembly::I64RegClass)
72283c26eaeSHeejin Ahn     return WebAssembly::COPY_I64;
72383c26eaeSHeejin Ahn   if (RC == &WebAssembly::F32RegClass)
72483c26eaeSHeejin Ahn     return WebAssembly::COPY_F32;
72583c26eaeSHeejin Ahn   if (RC == &WebAssembly::F64RegClass)
72683c26eaeSHeejin Ahn     return WebAssembly::COPY_F64;
72783c26eaeSHeejin Ahn   if (RC == &WebAssembly::V128RegClass)
72883c26eaeSHeejin Ahn     return WebAssembly::COPY_V128;
72960653e24SHeejin Ahn   if (RC == &WebAssembly::FUNCREFRegClass)
73060653e24SHeejin Ahn     return WebAssembly::COPY_FUNCREF;
73160653e24SHeejin Ahn   if (RC == &WebAssembly::EXTERNREFRegClass)
73260653e24SHeejin Ahn     return WebAssembly::COPY_EXTERNREF;
73383c26eaeSHeejin Ahn   llvm_unreachable("Unexpected register class");
73483c26eaeSHeejin Ahn }
73583c26eaeSHeejin Ahn 
73661d5c76aSHeejin Ahn // When MBB is split into MBB and Split, we should unstackify defs in MBB that
73761d5c76aSHeejin Ahn // have their uses in Split.
7389e4eadebSHeejin Ahn // FIXME This function will be used when fixing unwind mismatches, but the old
7399e4eadebSHeejin Ahn // version of that function was removed for the moment and the new version has
7409e4eadebSHeejin Ahn // not yet been added. So 'LLVM_ATTRIBUTE_UNUSED' is added to suppress the
7419e4eadebSHeejin Ahn // warning. Remove the attribute after the new functionality is added.
7429e4eadebSHeejin Ahn LLVM_ATTRIBUTE_UNUSED static void
743*1cc52357SHeejin Ahn unstackifyVRegsUsedInSplitBB(MachineBasicBlock &MBB, MachineBasicBlock &Split) {
744*1cc52357SHeejin Ahn   MachineFunction &MF = *MBB.getParent();
745*1cc52357SHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
746*1cc52357SHeejin Ahn   auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
747*1cc52357SHeejin Ahn   auto &MRI = MF.getRegInfo();
748*1cc52357SHeejin Ahn 
74961d5c76aSHeejin Ahn   for (auto &MI : Split) {
75061d5c76aSHeejin Ahn     for (auto &MO : MI.explicit_uses()) {
75161d5c76aSHeejin Ahn       if (!MO.isReg() || Register::isPhysicalRegister(MO.getReg()))
75261d5c76aSHeejin Ahn         continue;
75361d5c76aSHeejin Ahn       if (MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg()))
75461d5c76aSHeejin Ahn         if (Def->getParent() == &MBB)
75561d5c76aSHeejin Ahn           MFI.unstackifyVReg(MO.getReg());
75661d5c76aSHeejin Ahn     }
75761d5c76aSHeejin Ahn   }
75883c26eaeSHeejin Ahn 
75983c26eaeSHeejin Ahn   // In RegStackify, when a register definition is used multiple times,
76083c26eaeSHeejin Ahn   //    Reg = INST ...
76183c26eaeSHeejin Ahn   //    INST ..., Reg, ...
76283c26eaeSHeejin Ahn   //    INST ..., Reg, ...
76383c26eaeSHeejin Ahn   //    INST ..., Reg, ...
76483c26eaeSHeejin Ahn   //
76583c26eaeSHeejin Ahn   // we introduce a TEE, which has the following form:
76683c26eaeSHeejin Ahn   //    DefReg = INST ...
76783c26eaeSHeejin Ahn   //    TeeReg, Reg = TEE_... DefReg
76883c26eaeSHeejin Ahn   //    INST ..., TeeReg, ...
76983c26eaeSHeejin Ahn   //    INST ..., Reg, ...
77083c26eaeSHeejin Ahn   //    INST ..., Reg, ...
77183c26eaeSHeejin Ahn   // with DefReg and TeeReg stackified but Reg not stackified.
77283c26eaeSHeejin Ahn   //
77383c26eaeSHeejin Ahn   // But the invariant that TeeReg should be stackified can be violated while we
77483c26eaeSHeejin Ahn   // unstackify registers in the split BB above. In this case, we convert TEEs
77583c26eaeSHeejin Ahn   // into two COPYs. This COPY will be eventually eliminated in ExplicitLocals.
77683c26eaeSHeejin Ahn   //    DefReg = INST ...
77783c26eaeSHeejin Ahn   //    TeeReg = COPY DefReg
77883c26eaeSHeejin Ahn   //    Reg = COPY DefReg
77983c26eaeSHeejin Ahn   //    INST ..., TeeReg, ...
78083c26eaeSHeejin Ahn   //    INST ..., Reg, ...
78183c26eaeSHeejin Ahn   //    INST ..., Reg, ...
78283c26eaeSHeejin Ahn   for (auto I = MBB.begin(), E = MBB.end(); I != E;) {
78383c26eaeSHeejin Ahn     MachineInstr &MI = *I++;
78483c26eaeSHeejin Ahn     if (!WebAssembly::isTee(MI.getOpcode()))
78583c26eaeSHeejin Ahn       continue;
78683c26eaeSHeejin Ahn     Register TeeReg = MI.getOperand(0).getReg();
78783c26eaeSHeejin Ahn     Register Reg = MI.getOperand(1).getReg();
78883c26eaeSHeejin Ahn     Register DefReg = MI.getOperand(2).getReg();
78983c26eaeSHeejin Ahn     if (!MFI.isVRegStackified(TeeReg)) {
79083c26eaeSHeejin Ahn       // Now we are not using TEE anymore, so unstackify DefReg too
79183c26eaeSHeejin Ahn       MFI.unstackifyVReg(DefReg);
79283c26eaeSHeejin Ahn       unsigned CopyOpc = getCopyOpcode(MRI.getRegClass(DefReg));
79383c26eaeSHeejin Ahn       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), TeeReg)
79483c26eaeSHeejin Ahn           .addReg(DefReg);
79583c26eaeSHeejin Ahn       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), Reg).addReg(DefReg);
79683c26eaeSHeejin Ahn       MI.eraseFromParent();
79783c26eaeSHeejin Ahn     }
79883c26eaeSHeejin Ahn   }
79961d5c76aSHeejin Ahn }
80061d5c76aSHeejin Ahn 
801c4ac74fbSHeejin Ahn bool WebAssemblyCFGStackify::fixUnwindMismatches(MachineFunction &MF) {
8029e4eadebSHeejin Ahn   // TODO Implement this
803c4ac74fbSHeejin Ahn   return false;
804c4ac74fbSHeejin Ahn }
805c4ac74fbSHeejin Ahn 
8061d68e80fSDan Gohman static unsigned
80718c56a07SHeejin Ahn getDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
8081d68e80fSDan Gohman          const MachineBasicBlock *MBB) {
8091d68e80fSDan Gohman   unsigned Depth = 0;
8101d68e80fSDan Gohman   for (auto X : reverse(Stack)) {
8111d68e80fSDan Gohman     if (X == MBB)
8121d68e80fSDan Gohman       break;
8131d68e80fSDan Gohman     ++Depth;
8141d68e80fSDan Gohman   }
8151d68e80fSDan Gohman   assert(Depth < Stack.size() && "Branch destination should be in scope");
8161d68e80fSDan Gohman   return Depth;
8171d68e80fSDan Gohman }
8181d68e80fSDan Gohman 
8192726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable,
8202726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar,
8212726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of
8222726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks
8232726b88cSDan Gohman /// that end at the function end need to have a return type signature that
8242726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function
8252726b88cSDan Gohman /// checks for such cases and fixes up the signatures.
826e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) {
827e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
8282726b88cSDan Gohman 
8292726b88cSDan Gohman   if (MFI.getResults().empty())
8302726b88cSDan Gohman     return;
8312726b88cSDan Gohman 
8322cb27072SThomas Lively   // MCInstLower will add the proper types to multivalue signatures based on the
8332cb27072SThomas Lively   // function return type
8342cb27072SThomas Lively   WebAssembly::BlockType RetType =
8352cb27072SThomas Lively       MFI.getResults().size() > 1
8362cb27072SThomas Lively           ? WebAssembly::BlockType::Multivalue
8372cb27072SThomas Lively           : WebAssembly::BlockType(
8382cb27072SThomas Lively                 WebAssembly::toValType(MFI.getResults().front()));
8392726b88cSDan Gohman 
840d25c17f3SHeejin Ahn   SmallVector<MachineBasicBlock::reverse_iterator, 4> Worklist;
841d25c17f3SHeejin Ahn   Worklist.push_back(MF.rbegin()->rbegin());
842d25c17f3SHeejin Ahn 
843d25c17f3SHeejin Ahn   auto Process = [&](MachineBasicBlock::reverse_iterator It) {
844d25c17f3SHeejin Ahn     auto *MBB = It->getParent();
845d25c17f3SHeejin Ahn     while (It != MBB->rend()) {
846d25c17f3SHeejin Ahn       MachineInstr &MI = *It++;
847801bf7ebSShiva Chen       if (MI.isPosition() || MI.isDebugInstr())
8482726b88cSDan Gohman         continue;
8492cb27072SThomas Lively       switch (MI.getOpcode()) {
850d25c17f3SHeejin Ahn       case WebAssembly::END_TRY: {
851d25c17f3SHeejin Ahn         // If a 'try''s return type is fixed, both its try body and catch body
852d25c17f3SHeejin Ahn         // should satisfy the return type, so we need to search 'end'
853d25c17f3SHeejin Ahn         // instructions before its corresponding 'catch' too.
854d25c17f3SHeejin Ahn         auto *EHPad = TryToEHPad.lookup(EndToBegin[&MI]);
855d25c17f3SHeejin Ahn         assert(EHPad);
8569f8b2576SHeejin Ahn         auto NextIt =
8579f8b2576SHeejin Ahn             std::next(WebAssembly::findCatch(EHPad)->getReverseIterator());
8589f8b2576SHeejin Ahn         if (NextIt != EHPad->rend())
8599f8b2576SHeejin Ahn           Worklist.push_back(NextIt);
860d25c17f3SHeejin Ahn         LLVM_FALLTHROUGH;
861d25c17f3SHeejin Ahn       }
8622cb27072SThomas Lively       case WebAssembly::END_BLOCK:
8632cb27072SThomas Lively       case WebAssembly::END_LOOP:
86418c56a07SHeejin Ahn         EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
8652726b88cSDan Gohman         continue;
8662cb27072SThomas Lively       default:
867d25c17f3SHeejin Ahn         // Something other than an `end`. We're done for this BB.
8682726b88cSDan Gohman         return;
8692726b88cSDan Gohman       }
8702726b88cSDan Gohman     }
871d25c17f3SHeejin Ahn     // We've reached the beginning of a BB. Continue the search in the previous
872d25c17f3SHeejin Ahn     // BB.
873d25c17f3SHeejin Ahn     Worklist.push_back(MBB->getPrevNode()->rbegin());
874d25c17f3SHeejin Ahn   };
875d25c17f3SHeejin Ahn 
876d25c17f3SHeejin Ahn   while (!Worklist.empty())
877d25c17f3SHeejin Ahn     Process(Worklist.pop_back_val());
8782cb27072SThomas Lively }
8792726b88cSDan Gohman 
880d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body
881d934cb88SDan Gohman // were a block.
88218c56a07SHeejin Ahn static void appendEndToFunction(MachineFunction &MF,
883d934cb88SDan Gohman                                 const WebAssemblyInstrInfo &TII) {
88410b31358SDerek Schuff   BuildMI(MF.back(), MF.back().end(),
88510b31358SDerek Schuff           MF.back().findPrevDebugLoc(MF.back().end()),
886d934cb88SDan Gohman           TII.get(WebAssembly::END_FUNCTION));
887d934cb88SDan Gohman }
888d934cb88SDan Gohman 
889e76fa9ecSHeejin Ahn /// Insert LOOP/TRY/BLOCK markers at appropriate places.
890e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) {
891e76fa9ecSHeejin Ahn   // We allocate one more than the number of blocks in the function to
892e76fa9ecSHeejin Ahn   // accommodate for the possible fake block we may insert at the end.
893e76fa9ecSHeejin Ahn   ScopeTops.resize(MF.getNumBlockIDs() + 1);
8948fe7e86bSDan Gohman   // Place the LOOP for MBB if MBB is the header of a loop.
895e76fa9ecSHeejin Ahn   for (auto &MBB : MF)
896e76fa9ecSHeejin Ahn     placeLoopMarker(MBB);
89744a5a4b1SHeejin Ahn 
898d6f48786SHeejin Ahn   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
89944a5a4b1SHeejin Ahn   for (auto &MBB : MF) {
90044a5a4b1SHeejin Ahn     if (MBB.isEHPad()) {
90144a5a4b1SHeejin Ahn       // Place the TRY for MBB if MBB is the EH pad of an exception.
902e76fa9ecSHeejin Ahn       if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
903e76fa9ecSHeejin Ahn           MF.getFunction().hasPersonalityFn())
904e76fa9ecSHeejin Ahn         placeTryMarker(MBB);
90544a5a4b1SHeejin Ahn     } else {
90632807932SDan Gohman       // Place the BLOCK for MBB if MBB is branched to from above.
907e76fa9ecSHeejin Ahn       placeBlockMarker(MBB);
908950a13cfSDan Gohman     }
90944a5a4b1SHeejin Ahn   }
910c4ac74fbSHeejin Ahn   // Fix mismatches in unwind destinations induced by linearizing the code.
911daeead4bSHeejin Ahn   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
912daeead4bSHeejin Ahn       MF.getFunction().hasPersonalityFn())
913c4ac74fbSHeejin Ahn     fixUnwindMismatches(MF);
91444a5a4b1SHeejin Ahn }
915950a13cfSDan Gohman 
916e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) {
9171d68e80fSDan Gohman   // Now rewrite references to basic blocks to be depth immediates.
9181d68e80fSDan Gohman   SmallVector<const MachineBasicBlock *, 8> Stack;
9191d68e80fSDan Gohman   for (auto &MBB : reverse(MF)) {
920e76fa9ecSHeejin Ahn     for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) {
921e76fa9ecSHeejin Ahn       MachineInstr &MI = *I;
9221d68e80fSDan Gohman       switch (MI.getOpcode()) {
9231d68e80fSDan Gohman       case WebAssembly::BLOCK:
924e76fa9ecSHeejin Ahn       case WebAssembly::TRY:
925e76fa9ecSHeejin Ahn         assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <=
926e76fa9ecSHeejin Ahn                    MBB.getNumber() &&
927e76fa9ecSHeejin Ahn                "Block/try marker should be balanced");
928e76fa9ecSHeejin Ahn         Stack.pop_back();
929e76fa9ecSHeejin Ahn         break;
930e76fa9ecSHeejin Ahn 
9311d68e80fSDan Gohman       case WebAssembly::LOOP:
9321d68e80fSDan Gohman         assert(Stack.back() == &MBB && "Loop top should be balanced");
9331d68e80fSDan Gohman         Stack.pop_back();
9341d68e80fSDan Gohman         break;
935e76fa9ecSHeejin Ahn 
9361d68e80fSDan Gohman       case WebAssembly::END_BLOCK:
937e76fa9ecSHeejin Ahn       case WebAssembly::END_TRY:
9381d68e80fSDan Gohman         Stack.push_back(&MBB);
9391d68e80fSDan Gohman         break;
940e76fa9ecSHeejin Ahn 
9411d68e80fSDan Gohman       case WebAssembly::END_LOOP:
942e76fa9ecSHeejin Ahn         Stack.push_back(EndToBegin[&MI]->getParent());
9431d68e80fSDan Gohman         break;
944e76fa9ecSHeejin Ahn 
9451d68e80fSDan Gohman       default:
9461d68e80fSDan Gohman         if (MI.isTerminator()) {
9471d68e80fSDan Gohman           // Rewrite MBB operands to be depth immediates.
9481d68e80fSDan Gohman           SmallVector<MachineOperand, 4> Ops(MI.operands());
9491d68e80fSDan Gohman           while (MI.getNumOperands() > 0)
9501d68e80fSDan Gohman             MI.RemoveOperand(MI.getNumOperands() - 1);
9511d68e80fSDan Gohman           for (auto MO : Ops) {
9521d68e80fSDan Gohman             if (MO.isMBB())
95318c56a07SHeejin Ahn               MO = MachineOperand::CreateImm(getDepth(Stack, MO.getMBB()));
9541d68e80fSDan Gohman             MI.addOperand(MF, MO);
95532807932SDan Gohman           }
9561d68e80fSDan Gohman         }
9571d68e80fSDan Gohman         break;
9581d68e80fSDan Gohman       }
9591d68e80fSDan Gohman     }
9601d68e80fSDan Gohman   }
9611d68e80fSDan Gohman   assert(Stack.empty() && "Control flow should be balanced");
962e76fa9ecSHeejin Ahn }
9632726b88cSDan Gohman 
964e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::releaseMemory() {
965e76fa9ecSHeejin Ahn   ScopeTops.clear();
966e76fa9ecSHeejin Ahn   BeginToEnd.clear();
967e76fa9ecSHeejin Ahn   EndToBegin.clear();
968e76fa9ecSHeejin Ahn   TryToEHPad.clear();
969e76fa9ecSHeejin Ahn   EHPadToTry.clear();
970c4ac74fbSHeejin Ahn   AppendixBB = nullptr;
9711d68e80fSDan Gohman }
97232807932SDan Gohman 
973950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
974d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n"
975950a13cfSDan Gohman                        "********** Function: "
976950a13cfSDan Gohman                     << MF.getName() << '\n');
977cf699b45SHeejin Ahn   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
978950a13cfSDan Gohman 
979e76fa9ecSHeejin Ahn   releaseMemory();
980e76fa9ecSHeejin Ahn 
981e040533eSDan Gohman   // Liveness is not tracked for VALUE_STACK physreg.
9829c3bf318SDerek Schuff   MF.getRegInfo().invalidateLiveness();
983950a13cfSDan Gohman 
984e76fa9ecSHeejin Ahn   // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes.
985e76fa9ecSHeejin Ahn   placeMarkers(MF);
986e76fa9ecSHeejin Ahn 
987c4ac74fbSHeejin Ahn   // Remove unnecessary instructions possibly introduced by try/end_trys.
988cf699b45SHeejin Ahn   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
989cf699b45SHeejin Ahn       MF.getFunction().hasPersonalityFn())
990cf699b45SHeejin Ahn     removeUnnecessaryInstrs(MF);
991cf699b45SHeejin Ahn 
992e76fa9ecSHeejin Ahn   // Convert MBB operands in terminators to relative depth immediates.
993e76fa9ecSHeejin Ahn   rewriteDepthImmediates(MF);
994e76fa9ecSHeejin Ahn 
995e76fa9ecSHeejin Ahn   // Fix up block/loop/try signatures at the end of the function to conform to
996e76fa9ecSHeejin Ahn   // WebAssembly's rules.
997e76fa9ecSHeejin Ahn   fixEndsAtEndOfFunction(MF);
998e76fa9ecSHeejin Ahn 
999e76fa9ecSHeejin Ahn   // Add an end instruction at the end of the function body.
1000e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1001e76fa9ecSHeejin Ahn   if (!MF.getSubtarget<WebAssemblySubtarget>()
1002e76fa9ecSHeejin Ahn            .getTargetTriple()
1003e76fa9ecSHeejin Ahn            .isOSBinFormatELF())
100418c56a07SHeejin Ahn     appendEndToFunction(MF, TII);
100532807932SDan Gohman 
10061aaa481fSHeejin Ahn   MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified();
1007950a13cfSDan Gohman   return true;
1008950a13cfSDan Gohman }
1009