xref: /freebsd/contrib/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyCFGStackify.cpp (revision 0b57cec536236d46e3dba9bd041533462f33dbb7)
1*0b57cec5SDimitry Andric //===-- WebAssemblyCFGStackify.cpp - CFG Stackification -------------------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric ///
9*0b57cec5SDimitry Andric /// \file
10*0b57cec5SDimitry Andric /// This file implements a CFG stacking pass.
11*0b57cec5SDimitry Andric ///
12*0b57cec5SDimitry Andric /// This pass inserts BLOCK, LOOP, and TRY markers to mark the start of scopes,
13*0b57cec5SDimitry Andric /// since scope boundaries serve as the labels for WebAssembly's control
14*0b57cec5SDimitry Andric /// transfers.
15*0b57cec5SDimitry Andric ///
16*0b57cec5SDimitry Andric /// This is sufficient to convert arbitrary CFGs into a form that works on
17*0b57cec5SDimitry Andric /// WebAssembly, provided that all loops are single-entry.
18*0b57cec5SDimitry Andric ///
19*0b57cec5SDimitry Andric /// In case we use exceptions, this pass also fixes mismatches in unwind
20*0b57cec5SDimitry Andric /// destinations created during transforming CFG into wasm structured format.
21*0b57cec5SDimitry Andric ///
22*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
23*0b57cec5SDimitry Andric 
24*0b57cec5SDimitry Andric #include "WebAssembly.h"
25*0b57cec5SDimitry Andric #include "WebAssemblyExceptionInfo.h"
26*0b57cec5SDimitry Andric #include "WebAssemblyMachineFunctionInfo.h"
27*0b57cec5SDimitry Andric #include "WebAssemblySubtarget.h"
28*0b57cec5SDimitry Andric #include "WebAssemblyUtilities.h"
29*0b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
30*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
31*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
32*0b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
33*0b57cec5SDimitry Andric using namespace llvm;
34*0b57cec5SDimitry Andric 
35*0b57cec5SDimitry Andric #define DEBUG_TYPE "wasm-cfg-stackify"
36*0b57cec5SDimitry Andric 
37*0b57cec5SDimitry Andric STATISTIC(NumUnwindMismatches, "Number of EH pad unwind mismatches found");
38*0b57cec5SDimitry Andric 
39*0b57cec5SDimitry Andric namespace {
40*0b57cec5SDimitry Andric class WebAssemblyCFGStackify final : public MachineFunctionPass {
41*0b57cec5SDimitry Andric   StringRef getPassName() const override { return "WebAssembly CFG Stackify"; }
42*0b57cec5SDimitry Andric 
43*0b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
44*0b57cec5SDimitry Andric     AU.addRequired<MachineDominatorTree>();
45*0b57cec5SDimitry Andric     AU.addRequired<MachineLoopInfo>();
46*0b57cec5SDimitry Andric     AU.addRequired<WebAssemblyExceptionInfo>();
47*0b57cec5SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
48*0b57cec5SDimitry Andric   }
49*0b57cec5SDimitry Andric 
50*0b57cec5SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
51*0b57cec5SDimitry Andric 
52*0b57cec5SDimitry Andric   // For each block whose label represents the end of a scope, record the block
53*0b57cec5SDimitry Andric   // which holds the beginning of the scope. This will allow us to quickly skip
54*0b57cec5SDimitry Andric   // over scoped regions when walking blocks.
55*0b57cec5SDimitry Andric   SmallVector<MachineBasicBlock *, 8> ScopeTops;
56*0b57cec5SDimitry Andric 
57*0b57cec5SDimitry Andric   // Placing markers.
58*0b57cec5SDimitry Andric   void placeMarkers(MachineFunction &MF);
59*0b57cec5SDimitry Andric   void placeBlockMarker(MachineBasicBlock &MBB);
60*0b57cec5SDimitry Andric   void placeLoopMarker(MachineBasicBlock &MBB);
61*0b57cec5SDimitry Andric   void placeTryMarker(MachineBasicBlock &MBB);
62*0b57cec5SDimitry Andric   void removeUnnecessaryInstrs(MachineFunction &MF);
63*0b57cec5SDimitry Andric   bool fixUnwindMismatches(MachineFunction &MF);
64*0b57cec5SDimitry Andric   void rewriteDepthImmediates(MachineFunction &MF);
65*0b57cec5SDimitry Andric   void fixEndsAtEndOfFunction(MachineFunction &MF);
66*0b57cec5SDimitry Andric 
67*0b57cec5SDimitry Andric   // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY).
68*0b57cec5SDimitry Andric   DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd;
69*0b57cec5SDimitry Andric   // For each END_(BLOCK|LOOP|TRY), the corresponding BLOCK|LOOP|TRY.
70*0b57cec5SDimitry Andric   DenseMap<const MachineInstr *, MachineInstr *> EndToBegin;
71*0b57cec5SDimitry Andric   // <TRY marker, EH pad> map
72*0b57cec5SDimitry Andric   DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad;
73*0b57cec5SDimitry Andric   // <EH pad, TRY marker> map
74*0b57cec5SDimitry Andric   DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry;
75*0b57cec5SDimitry Andric 
76*0b57cec5SDimitry Andric   // There can be an appendix block at the end of each function, shared for:
77*0b57cec5SDimitry Andric   // - creating a correct signature for fallthrough returns
78*0b57cec5SDimitry Andric   // - target for rethrows that need to unwind to the caller, but are trapped
79*0b57cec5SDimitry Andric   //   inside another try/catch
80*0b57cec5SDimitry Andric   MachineBasicBlock *AppendixBB = nullptr;
81*0b57cec5SDimitry Andric   MachineBasicBlock *getAppendixBlock(MachineFunction &MF) {
82*0b57cec5SDimitry Andric     if (!AppendixBB) {
83*0b57cec5SDimitry Andric       AppendixBB = MF.CreateMachineBasicBlock();
84*0b57cec5SDimitry Andric       // Give it a fake predecessor so that AsmPrinter prints its label.
85*0b57cec5SDimitry Andric       AppendixBB->addSuccessor(AppendixBB);
86*0b57cec5SDimitry Andric       MF.push_back(AppendixBB);
87*0b57cec5SDimitry Andric     }
88*0b57cec5SDimitry Andric     return AppendixBB;
89*0b57cec5SDimitry Andric   }
90*0b57cec5SDimitry Andric 
91*0b57cec5SDimitry Andric   // Helper functions to register / unregister scope information created by
92*0b57cec5SDimitry Andric   // marker instructions.
93*0b57cec5SDimitry Andric   void registerScope(MachineInstr *Begin, MachineInstr *End);
94*0b57cec5SDimitry Andric   void registerTryScope(MachineInstr *Begin, MachineInstr *End,
95*0b57cec5SDimitry Andric                         MachineBasicBlock *EHPad);
96*0b57cec5SDimitry Andric   void unregisterScope(MachineInstr *Begin);
97*0b57cec5SDimitry Andric 
98*0b57cec5SDimitry Andric public:
99*0b57cec5SDimitry Andric   static char ID; // Pass identification, replacement for typeid
100*0b57cec5SDimitry Andric   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
101*0b57cec5SDimitry Andric   ~WebAssemblyCFGStackify() override { releaseMemory(); }
102*0b57cec5SDimitry Andric   void releaseMemory() override;
103*0b57cec5SDimitry Andric };
104*0b57cec5SDimitry Andric } // end anonymous namespace
105*0b57cec5SDimitry Andric 
106*0b57cec5SDimitry Andric char WebAssemblyCFGStackify::ID = 0;
107*0b57cec5SDimitry Andric INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE,
108*0b57cec5SDimitry Andric                 "Insert BLOCK/LOOP/TRY markers for WebAssembly scopes", false,
109*0b57cec5SDimitry Andric                 false)
110*0b57cec5SDimitry Andric 
111*0b57cec5SDimitry Andric FunctionPass *llvm::createWebAssemblyCFGStackify() {
112*0b57cec5SDimitry Andric   return new WebAssemblyCFGStackify();
113*0b57cec5SDimitry Andric }
114*0b57cec5SDimitry Andric 
115*0b57cec5SDimitry Andric /// Test whether Pred has any terminators explicitly branching to MBB, as
116*0b57cec5SDimitry Andric /// opposed to falling through. Note that it's possible (eg. in unoptimized
117*0b57cec5SDimitry Andric /// code) for a branch instruction to both branch to a block and fallthrough
118*0b57cec5SDimitry Andric /// to it, so we check the actual branch operands to see if there are any
119*0b57cec5SDimitry Andric /// explicit mentions.
120*0b57cec5SDimitry Andric static bool explicitlyBranchesTo(MachineBasicBlock *Pred,
121*0b57cec5SDimitry Andric                                  MachineBasicBlock *MBB) {
122*0b57cec5SDimitry Andric   for (MachineInstr &MI : Pred->terminators())
123*0b57cec5SDimitry Andric     for (MachineOperand &MO : MI.explicit_operands())
124*0b57cec5SDimitry Andric       if (MO.isMBB() && MO.getMBB() == MBB)
125*0b57cec5SDimitry Andric         return true;
126*0b57cec5SDimitry Andric   return false;
127*0b57cec5SDimitry Andric }
128*0b57cec5SDimitry Andric 
129*0b57cec5SDimitry Andric // Returns an iterator to the earliest position possible within the MBB,
130*0b57cec5SDimitry Andric // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
131*0b57cec5SDimitry Andric // contains instructions that should go before the marker, and AfterSet contains
132*0b57cec5SDimitry Andric // ones that should go after the marker. In this function, AfterSet is only
133*0b57cec5SDimitry Andric // used for sanity checking.
134*0b57cec5SDimitry Andric static MachineBasicBlock::iterator
135*0b57cec5SDimitry Andric getEarliestInsertPos(MachineBasicBlock *MBB,
136*0b57cec5SDimitry Andric                      const SmallPtrSet<const MachineInstr *, 4> &BeforeSet,
137*0b57cec5SDimitry Andric                      const SmallPtrSet<const MachineInstr *, 4> &AfterSet) {
138*0b57cec5SDimitry Andric   auto InsertPos = MBB->end();
139*0b57cec5SDimitry Andric   while (InsertPos != MBB->begin()) {
140*0b57cec5SDimitry Andric     if (BeforeSet.count(&*std::prev(InsertPos))) {
141*0b57cec5SDimitry Andric #ifndef NDEBUG
142*0b57cec5SDimitry Andric       // Sanity check
143*0b57cec5SDimitry Andric       for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos)
144*0b57cec5SDimitry Andric         assert(!AfterSet.count(&*std::prev(Pos)));
145*0b57cec5SDimitry Andric #endif
146*0b57cec5SDimitry Andric       break;
147*0b57cec5SDimitry Andric     }
148*0b57cec5SDimitry Andric     --InsertPos;
149*0b57cec5SDimitry Andric   }
150*0b57cec5SDimitry Andric   return InsertPos;
151*0b57cec5SDimitry Andric }
152*0b57cec5SDimitry Andric 
153*0b57cec5SDimitry Andric // Returns an iterator to the latest position possible within the MBB,
154*0b57cec5SDimitry Andric // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
155*0b57cec5SDimitry Andric // contains instructions that should go before the marker, and AfterSet contains
156*0b57cec5SDimitry Andric // ones that should go after the marker. In this function, BeforeSet is only
157*0b57cec5SDimitry Andric // used for sanity checking.
158*0b57cec5SDimitry Andric static MachineBasicBlock::iterator
159*0b57cec5SDimitry Andric getLatestInsertPos(MachineBasicBlock *MBB,
160*0b57cec5SDimitry Andric                    const SmallPtrSet<const MachineInstr *, 4> &BeforeSet,
161*0b57cec5SDimitry Andric                    const SmallPtrSet<const MachineInstr *, 4> &AfterSet) {
162*0b57cec5SDimitry Andric   auto InsertPos = MBB->begin();
163*0b57cec5SDimitry Andric   while (InsertPos != MBB->end()) {
164*0b57cec5SDimitry Andric     if (AfterSet.count(&*InsertPos)) {
165*0b57cec5SDimitry Andric #ifndef NDEBUG
166*0b57cec5SDimitry Andric       // Sanity check
167*0b57cec5SDimitry Andric       for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos)
168*0b57cec5SDimitry Andric         assert(!BeforeSet.count(&*Pos));
169*0b57cec5SDimitry Andric #endif
170*0b57cec5SDimitry Andric       break;
171*0b57cec5SDimitry Andric     }
172*0b57cec5SDimitry Andric     ++InsertPos;
173*0b57cec5SDimitry Andric   }
174*0b57cec5SDimitry Andric   return InsertPos;
175*0b57cec5SDimitry Andric }
176*0b57cec5SDimitry Andric 
177*0b57cec5SDimitry Andric void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin,
178*0b57cec5SDimitry Andric                                            MachineInstr *End) {
179*0b57cec5SDimitry Andric   BeginToEnd[Begin] = End;
180*0b57cec5SDimitry Andric   EndToBegin[End] = Begin;
181*0b57cec5SDimitry Andric }
182*0b57cec5SDimitry Andric 
183*0b57cec5SDimitry Andric void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin,
184*0b57cec5SDimitry Andric                                               MachineInstr *End,
185*0b57cec5SDimitry Andric                                               MachineBasicBlock *EHPad) {
186*0b57cec5SDimitry Andric   registerScope(Begin, End);
187*0b57cec5SDimitry Andric   TryToEHPad[Begin] = EHPad;
188*0b57cec5SDimitry Andric   EHPadToTry[EHPad] = Begin;
189*0b57cec5SDimitry Andric }
190*0b57cec5SDimitry Andric 
191*0b57cec5SDimitry Andric void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) {
192*0b57cec5SDimitry Andric   assert(BeginToEnd.count(Begin));
193*0b57cec5SDimitry Andric   MachineInstr *End = BeginToEnd[Begin];
194*0b57cec5SDimitry Andric   assert(EndToBegin.count(End));
195*0b57cec5SDimitry Andric   BeginToEnd.erase(Begin);
196*0b57cec5SDimitry Andric   EndToBegin.erase(End);
197*0b57cec5SDimitry Andric   MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin);
198*0b57cec5SDimitry Andric   if (EHPad) {
199*0b57cec5SDimitry Andric     assert(EHPadToTry.count(EHPad));
200*0b57cec5SDimitry Andric     TryToEHPad.erase(Begin);
201*0b57cec5SDimitry Andric     EHPadToTry.erase(EHPad);
202*0b57cec5SDimitry Andric   }
203*0b57cec5SDimitry Andric }
204*0b57cec5SDimitry Andric 
205*0b57cec5SDimitry Andric /// Insert a BLOCK marker for branches to MBB (if needed).
206*0b57cec5SDimitry Andric // TODO Consider a more generalized way of handling block (and also loop and
207*0b57cec5SDimitry Andric // try) signatures when we implement the multi-value proposal later.
208*0b57cec5SDimitry Andric void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) {
209*0b57cec5SDimitry Andric   assert(!MBB.isEHPad());
210*0b57cec5SDimitry Andric   MachineFunction &MF = *MBB.getParent();
211*0b57cec5SDimitry Andric   auto &MDT = getAnalysis<MachineDominatorTree>();
212*0b57cec5SDimitry Andric   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
213*0b57cec5SDimitry Andric   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
214*0b57cec5SDimitry Andric 
215*0b57cec5SDimitry Andric   // First compute the nearest common dominator of all forward non-fallthrough
216*0b57cec5SDimitry Andric   // predecessors so that we minimize the time that the BLOCK is on the stack,
217*0b57cec5SDimitry Andric   // which reduces overall stack height.
218*0b57cec5SDimitry Andric   MachineBasicBlock *Header = nullptr;
219*0b57cec5SDimitry Andric   bool IsBranchedTo = false;
220*0b57cec5SDimitry Andric   bool IsBrOnExn = false;
221*0b57cec5SDimitry Andric   MachineInstr *BrOnExn = nullptr;
222*0b57cec5SDimitry Andric   int MBBNumber = MBB.getNumber();
223*0b57cec5SDimitry Andric   for (MachineBasicBlock *Pred : MBB.predecessors()) {
224*0b57cec5SDimitry Andric     if (Pred->getNumber() < MBBNumber) {
225*0b57cec5SDimitry Andric       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
226*0b57cec5SDimitry Andric       if (explicitlyBranchesTo(Pred, &MBB)) {
227*0b57cec5SDimitry Andric         IsBranchedTo = true;
228*0b57cec5SDimitry Andric         if (Pred->getFirstTerminator()->getOpcode() == WebAssembly::BR_ON_EXN) {
229*0b57cec5SDimitry Andric           IsBrOnExn = true;
230*0b57cec5SDimitry Andric           assert(!BrOnExn && "There should be only one br_on_exn per block");
231*0b57cec5SDimitry Andric           BrOnExn = &*Pred->getFirstTerminator();
232*0b57cec5SDimitry Andric         }
233*0b57cec5SDimitry Andric       }
234*0b57cec5SDimitry Andric     }
235*0b57cec5SDimitry Andric   }
236*0b57cec5SDimitry Andric   if (!Header)
237*0b57cec5SDimitry Andric     return;
238*0b57cec5SDimitry Andric   if (!IsBranchedTo)
239*0b57cec5SDimitry Andric     return;
240*0b57cec5SDimitry Andric 
241*0b57cec5SDimitry Andric   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
242*0b57cec5SDimitry Andric   MachineBasicBlock *LayoutPred = MBB.getPrevNode();
243*0b57cec5SDimitry Andric 
244*0b57cec5SDimitry Andric   // If the nearest common dominator is inside a more deeply nested context,
245*0b57cec5SDimitry Andric   // walk out to the nearest scope which isn't more deeply nested.
246*0b57cec5SDimitry Andric   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
247*0b57cec5SDimitry Andric     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
248*0b57cec5SDimitry Andric       if (ScopeTop->getNumber() > Header->getNumber()) {
249*0b57cec5SDimitry Andric         // Skip over an intervening scope.
250*0b57cec5SDimitry Andric         I = std::next(ScopeTop->getIterator());
251*0b57cec5SDimitry Andric       } else {
252*0b57cec5SDimitry Andric         // We found a scope level at an appropriate depth.
253*0b57cec5SDimitry Andric         Header = ScopeTop;
254*0b57cec5SDimitry Andric         break;
255*0b57cec5SDimitry Andric       }
256*0b57cec5SDimitry Andric     }
257*0b57cec5SDimitry Andric   }
258*0b57cec5SDimitry Andric 
259*0b57cec5SDimitry Andric   // Decide where in Header to put the BLOCK.
260*0b57cec5SDimitry Andric 
261*0b57cec5SDimitry Andric   // Instructions that should go before the BLOCK.
262*0b57cec5SDimitry Andric   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
263*0b57cec5SDimitry Andric   // Instructions that should go after the BLOCK.
264*0b57cec5SDimitry Andric   SmallPtrSet<const MachineInstr *, 4> AfterSet;
265*0b57cec5SDimitry Andric   for (const auto &MI : *Header) {
266*0b57cec5SDimitry Andric     // If there is a previously placed LOOP marker and the bottom block of the
267*0b57cec5SDimitry Andric     // loop is above MBB, it should be after the BLOCK, because the loop is
268*0b57cec5SDimitry Andric     // nested in this BLOCK. Otherwise it should be before the BLOCK.
269*0b57cec5SDimitry Andric     if (MI.getOpcode() == WebAssembly::LOOP) {
270*0b57cec5SDimitry Andric       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
271*0b57cec5SDimitry Andric       if (MBB.getNumber() > LoopBottom->getNumber())
272*0b57cec5SDimitry Andric         AfterSet.insert(&MI);
273*0b57cec5SDimitry Andric #ifndef NDEBUG
274*0b57cec5SDimitry Andric       else
275*0b57cec5SDimitry Andric         BeforeSet.insert(&MI);
276*0b57cec5SDimitry Andric #endif
277*0b57cec5SDimitry Andric     }
278*0b57cec5SDimitry Andric 
279*0b57cec5SDimitry Andric     // All previously inserted BLOCK/TRY markers should be after the BLOCK
280*0b57cec5SDimitry Andric     // because they are all nested blocks.
281*0b57cec5SDimitry Andric     if (MI.getOpcode() == WebAssembly::BLOCK ||
282*0b57cec5SDimitry Andric         MI.getOpcode() == WebAssembly::TRY)
283*0b57cec5SDimitry Andric       AfterSet.insert(&MI);
284*0b57cec5SDimitry Andric 
285*0b57cec5SDimitry Andric #ifndef NDEBUG
286*0b57cec5SDimitry Andric     // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK.
287*0b57cec5SDimitry Andric     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
288*0b57cec5SDimitry Andric         MI.getOpcode() == WebAssembly::END_LOOP ||
289*0b57cec5SDimitry Andric         MI.getOpcode() == WebAssembly::END_TRY)
290*0b57cec5SDimitry Andric       BeforeSet.insert(&MI);
291*0b57cec5SDimitry Andric #endif
292*0b57cec5SDimitry Andric 
293*0b57cec5SDimitry Andric     // Terminators should go after the BLOCK.
294*0b57cec5SDimitry Andric     if (MI.isTerminator())
295*0b57cec5SDimitry Andric       AfterSet.insert(&MI);
296*0b57cec5SDimitry Andric   }
297*0b57cec5SDimitry Andric 
298*0b57cec5SDimitry Andric   // Local expression tree should go after the BLOCK.
299*0b57cec5SDimitry Andric   for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
300*0b57cec5SDimitry Andric        --I) {
301*0b57cec5SDimitry Andric     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
302*0b57cec5SDimitry Andric       continue;
303*0b57cec5SDimitry Andric     if (WebAssembly::isChild(*std::prev(I), MFI))
304*0b57cec5SDimitry Andric       AfterSet.insert(&*std::prev(I));
305*0b57cec5SDimitry Andric     else
306*0b57cec5SDimitry Andric       break;
307*0b57cec5SDimitry Andric   }
308*0b57cec5SDimitry Andric 
309*0b57cec5SDimitry Andric   // Add the BLOCK.
310*0b57cec5SDimitry Andric 
311*0b57cec5SDimitry Andric   // 'br_on_exn' extracts exnref object and pushes variable number of values
312*0b57cec5SDimitry Andric   // depending on its tag. For C++ exception, its a single i32 value, and the
313*0b57cec5SDimitry Andric   // generated code will be in the form of:
314*0b57cec5SDimitry Andric   // block i32
315*0b57cec5SDimitry Andric   //   br_on_exn 0, $__cpp_exception
316*0b57cec5SDimitry Andric   //   rethrow
317*0b57cec5SDimitry Andric   // end_block
318*0b57cec5SDimitry Andric   WebAssembly::ExprType ReturnType = WebAssembly::ExprType::Void;
319*0b57cec5SDimitry Andric   if (IsBrOnExn) {
320*0b57cec5SDimitry Andric     const char *TagName = BrOnExn->getOperand(1).getSymbolName();
321*0b57cec5SDimitry Andric     if (std::strcmp(TagName, "__cpp_exception") != 0)
322*0b57cec5SDimitry Andric       llvm_unreachable("Only C++ exception is supported");
323*0b57cec5SDimitry Andric     ReturnType = WebAssembly::ExprType::I32;
324*0b57cec5SDimitry Andric   }
325*0b57cec5SDimitry Andric 
326*0b57cec5SDimitry Andric   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
327*0b57cec5SDimitry Andric   MachineInstr *Begin =
328*0b57cec5SDimitry Andric       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
329*0b57cec5SDimitry Andric               TII.get(WebAssembly::BLOCK))
330*0b57cec5SDimitry Andric           .addImm(int64_t(ReturnType));
331*0b57cec5SDimitry Andric 
332*0b57cec5SDimitry Andric   // Decide where in Header to put the END_BLOCK.
333*0b57cec5SDimitry Andric   BeforeSet.clear();
334*0b57cec5SDimitry Andric   AfterSet.clear();
335*0b57cec5SDimitry Andric   for (auto &MI : MBB) {
336*0b57cec5SDimitry Andric #ifndef NDEBUG
337*0b57cec5SDimitry Andric     // END_BLOCK should precede existing LOOP and TRY markers.
338*0b57cec5SDimitry Andric     if (MI.getOpcode() == WebAssembly::LOOP ||
339*0b57cec5SDimitry Andric         MI.getOpcode() == WebAssembly::TRY)
340*0b57cec5SDimitry Andric       AfterSet.insert(&MI);
341*0b57cec5SDimitry Andric #endif
342*0b57cec5SDimitry Andric 
343*0b57cec5SDimitry Andric     // If there is a previously placed END_LOOP marker and the header of the
344*0b57cec5SDimitry Andric     // loop is above this block's header, the END_LOOP should be placed after
345*0b57cec5SDimitry Andric     // the BLOCK, because the loop contains this block. Otherwise the END_LOOP
346*0b57cec5SDimitry Andric     // should be placed before the BLOCK. The same for END_TRY.
347*0b57cec5SDimitry Andric     if (MI.getOpcode() == WebAssembly::END_LOOP ||
348*0b57cec5SDimitry Andric         MI.getOpcode() == WebAssembly::END_TRY) {
349*0b57cec5SDimitry Andric       if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
350*0b57cec5SDimitry Andric         BeforeSet.insert(&MI);
351*0b57cec5SDimitry Andric #ifndef NDEBUG
352*0b57cec5SDimitry Andric       else
353*0b57cec5SDimitry Andric         AfterSet.insert(&MI);
354*0b57cec5SDimitry Andric #endif
355*0b57cec5SDimitry Andric     }
356*0b57cec5SDimitry Andric   }
357*0b57cec5SDimitry Andric 
358*0b57cec5SDimitry Andric   // Mark the end of the block.
359*0b57cec5SDimitry Andric   InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
360*0b57cec5SDimitry Andric   MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
361*0b57cec5SDimitry Andric                               TII.get(WebAssembly::END_BLOCK));
362*0b57cec5SDimitry Andric   registerScope(Begin, End);
363*0b57cec5SDimitry Andric 
364*0b57cec5SDimitry Andric   // Track the farthest-spanning scope that ends at this point.
365*0b57cec5SDimitry Andric   int Number = MBB.getNumber();
366*0b57cec5SDimitry Andric   if (!ScopeTops[Number] ||
367*0b57cec5SDimitry Andric       ScopeTops[Number]->getNumber() > Header->getNumber())
368*0b57cec5SDimitry Andric     ScopeTops[Number] = Header;
369*0b57cec5SDimitry Andric }
370*0b57cec5SDimitry Andric 
371*0b57cec5SDimitry Andric /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
372*0b57cec5SDimitry Andric void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) {
373*0b57cec5SDimitry Andric   MachineFunction &MF = *MBB.getParent();
374*0b57cec5SDimitry Andric   const auto &MLI = getAnalysis<MachineLoopInfo>();
375*0b57cec5SDimitry Andric   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
376*0b57cec5SDimitry Andric 
377*0b57cec5SDimitry Andric   MachineLoop *Loop = MLI.getLoopFor(&MBB);
378*0b57cec5SDimitry Andric   if (!Loop || Loop->getHeader() != &MBB)
379*0b57cec5SDimitry Andric     return;
380*0b57cec5SDimitry Andric 
381*0b57cec5SDimitry Andric   // The operand of a LOOP is the first block after the loop. If the loop is the
382*0b57cec5SDimitry Andric   // bottom of the function, insert a dummy block at the end.
383*0b57cec5SDimitry Andric   MachineBasicBlock *Bottom = WebAssembly::getBottom(Loop);
384*0b57cec5SDimitry Andric   auto Iter = std::next(Bottom->getIterator());
385*0b57cec5SDimitry Andric   if (Iter == MF.end()) {
386*0b57cec5SDimitry Andric     getAppendixBlock(MF);
387*0b57cec5SDimitry Andric     Iter = std::next(Bottom->getIterator());
388*0b57cec5SDimitry Andric   }
389*0b57cec5SDimitry Andric   MachineBasicBlock *AfterLoop = &*Iter;
390*0b57cec5SDimitry Andric 
391*0b57cec5SDimitry Andric   // Decide where in Header to put the LOOP.
392*0b57cec5SDimitry Andric   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
393*0b57cec5SDimitry Andric   SmallPtrSet<const MachineInstr *, 4> AfterSet;
394*0b57cec5SDimitry Andric   for (const auto &MI : MBB) {
395*0b57cec5SDimitry Andric     // LOOP marker should be after any existing loop that ends here. Otherwise
396*0b57cec5SDimitry Andric     // we assume the instruction belongs to the loop.
397*0b57cec5SDimitry Andric     if (MI.getOpcode() == WebAssembly::END_LOOP)
398*0b57cec5SDimitry Andric       BeforeSet.insert(&MI);
399*0b57cec5SDimitry Andric #ifndef NDEBUG
400*0b57cec5SDimitry Andric     else
401*0b57cec5SDimitry Andric       AfterSet.insert(&MI);
402*0b57cec5SDimitry Andric #endif
403*0b57cec5SDimitry Andric   }
404*0b57cec5SDimitry Andric 
405*0b57cec5SDimitry Andric   // Mark the beginning of the loop.
406*0b57cec5SDimitry Andric   auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
407*0b57cec5SDimitry Andric   MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos),
408*0b57cec5SDimitry Andric                                 TII.get(WebAssembly::LOOP))
409*0b57cec5SDimitry Andric                             .addImm(int64_t(WebAssembly::ExprType::Void));
410*0b57cec5SDimitry Andric 
411*0b57cec5SDimitry Andric   // Decide where in Header to put the END_LOOP.
412*0b57cec5SDimitry Andric   BeforeSet.clear();
413*0b57cec5SDimitry Andric   AfterSet.clear();
414*0b57cec5SDimitry Andric #ifndef NDEBUG
415*0b57cec5SDimitry Andric   for (const auto &MI : MBB)
416*0b57cec5SDimitry Andric     // Existing END_LOOP markers belong to parent loops of this loop
417*0b57cec5SDimitry Andric     if (MI.getOpcode() == WebAssembly::END_LOOP)
418*0b57cec5SDimitry Andric       AfterSet.insert(&MI);
419*0b57cec5SDimitry Andric #endif
420*0b57cec5SDimitry Andric 
421*0b57cec5SDimitry Andric   // Mark the end of the loop (using arbitrary debug location that branched to
422*0b57cec5SDimitry Andric   // the loop end as its location).
423*0b57cec5SDimitry Andric   InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet);
424*0b57cec5SDimitry Andric   DebugLoc EndDL = AfterLoop->pred_empty()
425*0b57cec5SDimitry Andric                        ? DebugLoc()
426*0b57cec5SDimitry Andric                        : (*AfterLoop->pred_rbegin())->findBranchDebugLoc();
427*0b57cec5SDimitry Andric   MachineInstr *End =
428*0b57cec5SDimitry Andric       BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP));
429*0b57cec5SDimitry Andric   registerScope(Begin, End);
430*0b57cec5SDimitry Andric 
431*0b57cec5SDimitry Andric   assert((!ScopeTops[AfterLoop->getNumber()] ||
432*0b57cec5SDimitry Andric           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
433*0b57cec5SDimitry Andric          "With block sorting the outermost loop for a block should be first.");
434*0b57cec5SDimitry Andric   if (!ScopeTops[AfterLoop->getNumber()])
435*0b57cec5SDimitry Andric     ScopeTops[AfterLoop->getNumber()] = &MBB;
436*0b57cec5SDimitry Andric }
437*0b57cec5SDimitry Andric 
438*0b57cec5SDimitry Andric void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) {
439*0b57cec5SDimitry Andric   assert(MBB.isEHPad());
440*0b57cec5SDimitry Andric   MachineFunction &MF = *MBB.getParent();
441*0b57cec5SDimitry Andric   auto &MDT = getAnalysis<MachineDominatorTree>();
442*0b57cec5SDimitry Andric   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
443*0b57cec5SDimitry Andric   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
444*0b57cec5SDimitry Andric   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
445*0b57cec5SDimitry Andric 
446*0b57cec5SDimitry Andric   // Compute the nearest common dominator of all unwind predecessors
447*0b57cec5SDimitry Andric   MachineBasicBlock *Header = nullptr;
448*0b57cec5SDimitry Andric   int MBBNumber = MBB.getNumber();
449*0b57cec5SDimitry Andric   for (auto *Pred : MBB.predecessors()) {
450*0b57cec5SDimitry Andric     if (Pred->getNumber() < MBBNumber) {
451*0b57cec5SDimitry Andric       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
452*0b57cec5SDimitry Andric       assert(!explicitlyBranchesTo(Pred, &MBB) &&
453*0b57cec5SDimitry Andric              "Explicit branch to an EH pad!");
454*0b57cec5SDimitry Andric     }
455*0b57cec5SDimitry Andric   }
456*0b57cec5SDimitry Andric   if (!Header)
457*0b57cec5SDimitry Andric     return;
458*0b57cec5SDimitry Andric 
459*0b57cec5SDimitry Andric   // If this try is at the bottom of the function, insert a dummy block at the
460*0b57cec5SDimitry Andric   // end.
461*0b57cec5SDimitry Andric   WebAssemblyException *WE = WEI.getExceptionFor(&MBB);
462*0b57cec5SDimitry Andric   assert(WE);
463*0b57cec5SDimitry Andric   MachineBasicBlock *Bottom = WebAssembly::getBottom(WE);
464*0b57cec5SDimitry Andric 
465*0b57cec5SDimitry Andric   auto Iter = std::next(Bottom->getIterator());
466*0b57cec5SDimitry Andric   if (Iter == MF.end()) {
467*0b57cec5SDimitry Andric     getAppendixBlock(MF);
468*0b57cec5SDimitry Andric     Iter = std::next(Bottom->getIterator());
469*0b57cec5SDimitry Andric   }
470*0b57cec5SDimitry Andric   MachineBasicBlock *Cont = &*Iter;
471*0b57cec5SDimitry Andric 
472*0b57cec5SDimitry Andric   assert(Cont != &MF.front());
473*0b57cec5SDimitry Andric   MachineBasicBlock *LayoutPred = Cont->getPrevNode();
474*0b57cec5SDimitry Andric 
475*0b57cec5SDimitry Andric   // If the nearest common dominator is inside a more deeply nested context,
476*0b57cec5SDimitry Andric   // walk out to the nearest scope which isn't more deeply nested.
477*0b57cec5SDimitry Andric   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
478*0b57cec5SDimitry Andric     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
479*0b57cec5SDimitry Andric       if (ScopeTop->getNumber() > Header->getNumber()) {
480*0b57cec5SDimitry Andric         // Skip over an intervening scope.
481*0b57cec5SDimitry Andric         I = std::next(ScopeTop->getIterator());
482*0b57cec5SDimitry Andric       } else {
483*0b57cec5SDimitry Andric         // We found a scope level at an appropriate depth.
484*0b57cec5SDimitry Andric         Header = ScopeTop;
485*0b57cec5SDimitry Andric         break;
486*0b57cec5SDimitry Andric       }
487*0b57cec5SDimitry Andric     }
488*0b57cec5SDimitry Andric   }
489*0b57cec5SDimitry Andric 
490*0b57cec5SDimitry Andric   // Decide where in Header to put the TRY.
491*0b57cec5SDimitry Andric 
492*0b57cec5SDimitry Andric   // Instructions that should go before the TRY.
493*0b57cec5SDimitry Andric   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
494*0b57cec5SDimitry Andric   // Instructions that should go after the TRY.
495*0b57cec5SDimitry Andric   SmallPtrSet<const MachineInstr *, 4> AfterSet;
496*0b57cec5SDimitry Andric   for (const auto &MI : *Header) {
497*0b57cec5SDimitry Andric     // If there is a previously placed LOOP marker and the bottom block of the
498*0b57cec5SDimitry Andric     // loop is above MBB, it should be after the TRY, because the loop is nested
499*0b57cec5SDimitry Andric     // in this TRY. Otherwise it should be before the TRY.
500*0b57cec5SDimitry Andric     if (MI.getOpcode() == WebAssembly::LOOP) {
501*0b57cec5SDimitry Andric       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
502*0b57cec5SDimitry Andric       if (MBB.getNumber() > LoopBottom->getNumber())
503*0b57cec5SDimitry Andric         AfterSet.insert(&MI);
504*0b57cec5SDimitry Andric #ifndef NDEBUG
505*0b57cec5SDimitry Andric       else
506*0b57cec5SDimitry Andric         BeforeSet.insert(&MI);
507*0b57cec5SDimitry Andric #endif
508*0b57cec5SDimitry Andric     }
509*0b57cec5SDimitry Andric 
510*0b57cec5SDimitry Andric     // All previously inserted BLOCK/TRY markers should be after the TRY because
511*0b57cec5SDimitry Andric     // they are all nested trys.
512*0b57cec5SDimitry Andric     if (MI.getOpcode() == WebAssembly::BLOCK ||
513*0b57cec5SDimitry Andric         MI.getOpcode() == WebAssembly::TRY)
514*0b57cec5SDimitry Andric       AfterSet.insert(&MI);
515*0b57cec5SDimitry Andric 
516*0b57cec5SDimitry Andric #ifndef NDEBUG
517*0b57cec5SDimitry Andric     // All END_(BLOCK/LOOP/TRY) markers should be before the TRY.
518*0b57cec5SDimitry Andric     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
519*0b57cec5SDimitry Andric         MI.getOpcode() == WebAssembly::END_LOOP ||
520*0b57cec5SDimitry Andric         MI.getOpcode() == WebAssembly::END_TRY)
521*0b57cec5SDimitry Andric       BeforeSet.insert(&MI);
522*0b57cec5SDimitry Andric #endif
523*0b57cec5SDimitry Andric 
524*0b57cec5SDimitry Andric     // Terminators should go after the TRY.
525*0b57cec5SDimitry Andric     if (MI.isTerminator())
526*0b57cec5SDimitry Andric       AfterSet.insert(&MI);
527*0b57cec5SDimitry Andric   }
528*0b57cec5SDimitry Andric 
529*0b57cec5SDimitry Andric   // Local expression tree should go after the TRY.
530*0b57cec5SDimitry Andric   for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
531*0b57cec5SDimitry Andric        --I) {
532*0b57cec5SDimitry Andric     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
533*0b57cec5SDimitry Andric       continue;
534*0b57cec5SDimitry Andric     if (WebAssembly::isChild(*std::prev(I), MFI))
535*0b57cec5SDimitry Andric       AfterSet.insert(&*std::prev(I));
536*0b57cec5SDimitry Andric     else
537*0b57cec5SDimitry Andric       break;
538*0b57cec5SDimitry Andric   }
539*0b57cec5SDimitry Andric 
540*0b57cec5SDimitry Andric   // If Header unwinds to MBB (= Header contains 'invoke'), the try block should
541*0b57cec5SDimitry Andric   // contain the call within it. So the call should go after the TRY. The
542*0b57cec5SDimitry Andric   // exception is when the header's terminator is a rethrow instruction, in
543*0b57cec5SDimitry Andric   // which case that instruction, not a call instruction before it, is gonna
544*0b57cec5SDimitry Andric   // throw.
545*0b57cec5SDimitry Andric   if (MBB.isPredecessor(Header)) {
546*0b57cec5SDimitry Andric     auto TermPos = Header->getFirstTerminator();
547*0b57cec5SDimitry Andric     if (TermPos == Header->end() ||
548*0b57cec5SDimitry Andric         TermPos->getOpcode() != WebAssembly::RETHROW) {
549*0b57cec5SDimitry Andric       for (const auto &MI : reverse(*Header)) {
550*0b57cec5SDimitry Andric         if (MI.isCall()) {
551*0b57cec5SDimitry Andric           AfterSet.insert(&MI);
552*0b57cec5SDimitry Andric           // Possibly throwing calls are usually wrapped by EH_LABEL
553*0b57cec5SDimitry Andric           // instructions. We don't want to split them and the call.
554*0b57cec5SDimitry Andric           if (MI.getIterator() != Header->begin() &&
555*0b57cec5SDimitry Andric               std::prev(MI.getIterator())->isEHLabel())
556*0b57cec5SDimitry Andric             AfterSet.insert(&*std::prev(MI.getIterator()));
557*0b57cec5SDimitry Andric           break;
558*0b57cec5SDimitry Andric         }
559*0b57cec5SDimitry Andric       }
560*0b57cec5SDimitry Andric     }
561*0b57cec5SDimitry Andric   }
562*0b57cec5SDimitry Andric 
563*0b57cec5SDimitry Andric   // Add the TRY.
564*0b57cec5SDimitry Andric   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
565*0b57cec5SDimitry Andric   MachineInstr *Begin =
566*0b57cec5SDimitry Andric       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
567*0b57cec5SDimitry Andric               TII.get(WebAssembly::TRY))
568*0b57cec5SDimitry Andric           .addImm(int64_t(WebAssembly::ExprType::Void));
569*0b57cec5SDimitry Andric 
570*0b57cec5SDimitry Andric   // Decide where in Header to put the END_TRY.
571*0b57cec5SDimitry Andric   BeforeSet.clear();
572*0b57cec5SDimitry Andric   AfterSet.clear();
573*0b57cec5SDimitry Andric   for (const auto &MI : *Cont) {
574*0b57cec5SDimitry Andric #ifndef NDEBUG
575*0b57cec5SDimitry Andric     // END_TRY should precede existing LOOP and BLOCK markers.
576*0b57cec5SDimitry Andric     if (MI.getOpcode() == WebAssembly::LOOP ||
577*0b57cec5SDimitry Andric         MI.getOpcode() == WebAssembly::BLOCK)
578*0b57cec5SDimitry Andric       AfterSet.insert(&MI);
579*0b57cec5SDimitry Andric 
580*0b57cec5SDimitry Andric     // All END_TRY markers placed earlier belong to exceptions that contains
581*0b57cec5SDimitry Andric     // this one.
582*0b57cec5SDimitry Andric     if (MI.getOpcode() == WebAssembly::END_TRY)
583*0b57cec5SDimitry Andric       AfterSet.insert(&MI);
584*0b57cec5SDimitry Andric #endif
585*0b57cec5SDimitry Andric 
586*0b57cec5SDimitry Andric     // If there is a previously placed END_LOOP marker and its header is after
587*0b57cec5SDimitry Andric     // where TRY marker is, this loop is contained within the 'catch' part, so
588*0b57cec5SDimitry Andric     // the END_TRY marker should go after that. Otherwise, the whole try-catch
589*0b57cec5SDimitry Andric     // is contained within this loop, so the END_TRY should go before that.
590*0b57cec5SDimitry Andric     if (MI.getOpcode() == WebAssembly::END_LOOP) {
591*0b57cec5SDimitry Andric       // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they
592*0b57cec5SDimitry Andric       // are in the same BB, LOOP is always before TRY.
593*0b57cec5SDimitry Andric       if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber())
594*0b57cec5SDimitry Andric         BeforeSet.insert(&MI);
595*0b57cec5SDimitry Andric #ifndef NDEBUG
596*0b57cec5SDimitry Andric       else
597*0b57cec5SDimitry Andric         AfterSet.insert(&MI);
598*0b57cec5SDimitry Andric #endif
599*0b57cec5SDimitry Andric     }
600*0b57cec5SDimitry Andric 
601*0b57cec5SDimitry Andric     // It is not possible for an END_BLOCK to be already in this block.
602*0b57cec5SDimitry Andric   }
603*0b57cec5SDimitry Andric 
604*0b57cec5SDimitry Andric   // Mark the end of the TRY.
605*0b57cec5SDimitry Andric   InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet);
606*0b57cec5SDimitry Andric   MachineInstr *End =
607*0b57cec5SDimitry Andric       BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(),
608*0b57cec5SDimitry Andric               TII.get(WebAssembly::END_TRY));
609*0b57cec5SDimitry Andric   registerTryScope(Begin, End, &MBB);
610*0b57cec5SDimitry Andric 
611*0b57cec5SDimitry Andric   // Track the farthest-spanning scope that ends at this point. We create two
612*0b57cec5SDimitry Andric   // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB
613*0b57cec5SDimitry Andric   // with 'try'). We need to create 'catch' -> 'try' mapping here too because
614*0b57cec5SDimitry Andric   // markers should not span across 'catch'. For example, this should not
615*0b57cec5SDimitry Andric   // happen:
616*0b57cec5SDimitry Andric   //
617*0b57cec5SDimitry Andric   // try
618*0b57cec5SDimitry Andric   //   block     --|  (X)
619*0b57cec5SDimitry Andric   // catch         |
620*0b57cec5SDimitry Andric   //   end_block --|
621*0b57cec5SDimitry Andric   // end_try
622*0b57cec5SDimitry Andric   for (int Number : {Cont->getNumber(), MBB.getNumber()}) {
623*0b57cec5SDimitry Andric     if (!ScopeTops[Number] ||
624*0b57cec5SDimitry Andric         ScopeTops[Number]->getNumber() > Header->getNumber())
625*0b57cec5SDimitry Andric       ScopeTops[Number] = Header;
626*0b57cec5SDimitry Andric   }
627*0b57cec5SDimitry Andric }
628*0b57cec5SDimitry Andric 
629*0b57cec5SDimitry Andric void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) {
630*0b57cec5SDimitry Andric   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
631*0b57cec5SDimitry Andric 
632*0b57cec5SDimitry Andric   // When there is an unconditional branch right before a catch instruction and
633*0b57cec5SDimitry Andric   // it branches to the end of end_try marker, we don't need the branch, because
634*0b57cec5SDimitry Andric   // it there is no exception, the control flow transfers to that point anyway.
635*0b57cec5SDimitry Andric   // bb0:
636*0b57cec5SDimitry Andric   //   try
637*0b57cec5SDimitry Andric   //     ...
638*0b57cec5SDimitry Andric   //     br bb2      <- Not necessary
639*0b57cec5SDimitry Andric   // bb1:
640*0b57cec5SDimitry Andric   //   catch
641*0b57cec5SDimitry Andric   //     ...
642*0b57cec5SDimitry Andric   // bb2:
643*0b57cec5SDimitry Andric   //   end
644*0b57cec5SDimitry Andric   for (auto &MBB : MF) {
645*0b57cec5SDimitry Andric     if (!MBB.isEHPad())
646*0b57cec5SDimitry Andric       continue;
647*0b57cec5SDimitry Andric 
648*0b57cec5SDimitry Andric     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
649*0b57cec5SDimitry Andric     SmallVector<MachineOperand, 4> Cond;
650*0b57cec5SDimitry Andric     MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode();
651*0b57cec5SDimitry Andric     MachineBasicBlock *Cont = BeginToEnd[EHPadToTry[&MBB]]->getParent();
652*0b57cec5SDimitry Andric     bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond);
653*0b57cec5SDimitry Andric     if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) ||
654*0b57cec5SDimitry Andric                        (!Cond.empty() && FBB && FBB == Cont)))
655*0b57cec5SDimitry Andric       TII.removeBranch(*EHPadLayoutPred);
656*0b57cec5SDimitry Andric   }
657*0b57cec5SDimitry Andric 
658*0b57cec5SDimitry Andric   // When there are block / end_block markers that overlap with try / end_try
659*0b57cec5SDimitry Andric   // markers, and the block and try markers' return types are the same, the
660*0b57cec5SDimitry Andric   // block /end_block markers are not necessary, because try / end_try markers
661*0b57cec5SDimitry Andric   // also can serve as boundaries for branches.
662*0b57cec5SDimitry Andric   // block         <- Not necessary
663*0b57cec5SDimitry Andric   //   try
664*0b57cec5SDimitry Andric   //     ...
665*0b57cec5SDimitry Andric   //   catch
666*0b57cec5SDimitry Andric   //     ...
667*0b57cec5SDimitry Andric   //   end
668*0b57cec5SDimitry Andric   // end           <- Not necessary
669*0b57cec5SDimitry Andric   SmallVector<MachineInstr *, 32> ToDelete;
670*0b57cec5SDimitry Andric   for (auto &MBB : MF) {
671*0b57cec5SDimitry Andric     for (auto &MI : MBB) {
672*0b57cec5SDimitry Andric       if (MI.getOpcode() != WebAssembly::TRY)
673*0b57cec5SDimitry Andric         continue;
674*0b57cec5SDimitry Andric 
675*0b57cec5SDimitry Andric       MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try];
676*0b57cec5SDimitry Andric       MachineBasicBlock *TryBB = Try->getParent();
677*0b57cec5SDimitry Andric       MachineBasicBlock *Cont = EndTry->getParent();
678*0b57cec5SDimitry Andric       int64_t RetType = Try->getOperand(0).getImm();
679*0b57cec5SDimitry Andric       for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator());
680*0b57cec5SDimitry Andric            B != TryBB->begin() && E != Cont->end() &&
681*0b57cec5SDimitry Andric            std::prev(B)->getOpcode() == WebAssembly::BLOCK &&
682*0b57cec5SDimitry Andric            E->getOpcode() == WebAssembly::END_BLOCK &&
683*0b57cec5SDimitry Andric            std::prev(B)->getOperand(0).getImm() == RetType;
684*0b57cec5SDimitry Andric            --B, ++E) {
685*0b57cec5SDimitry Andric         ToDelete.push_back(&*std::prev(B));
686*0b57cec5SDimitry Andric         ToDelete.push_back(&*E);
687*0b57cec5SDimitry Andric       }
688*0b57cec5SDimitry Andric     }
689*0b57cec5SDimitry Andric   }
690*0b57cec5SDimitry Andric   for (auto *MI : ToDelete) {
691*0b57cec5SDimitry Andric     if (MI->getOpcode() == WebAssembly::BLOCK)
692*0b57cec5SDimitry Andric       unregisterScope(MI);
693*0b57cec5SDimitry Andric     MI->eraseFromParent();
694*0b57cec5SDimitry Andric   }
695*0b57cec5SDimitry Andric }
696*0b57cec5SDimitry Andric 
697*0b57cec5SDimitry Andric bool WebAssemblyCFGStackify::fixUnwindMismatches(MachineFunction &MF) {
698*0b57cec5SDimitry Andric   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
699*0b57cec5SDimitry Andric   MachineRegisterInfo &MRI = MF.getRegInfo();
700*0b57cec5SDimitry Andric 
701*0b57cec5SDimitry Andric   // Linearizing the control flow by placing TRY / END_TRY markers can create
702*0b57cec5SDimitry Andric   // mismatches in unwind destinations. There are two kinds of mismatches we
703*0b57cec5SDimitry Andric   // try to solve here.
704*0b57cec5SDimitry Andric 
705*0b57cec5SDimitry Andric   // 1. When an instruction may throw, but the EH pad it will unwind to can be
706*0b57cec5SDimitry Andric   //    different from the original CFG.
707*0b57cec5SDimitry Andric   //
708*0b57cec5SDimitry Andric   // Example: we have the following CFG:
709*0b57cec5SDimitry Andric   // bb0:
710*0b57cec5SDimitry Andric   //   call @foo (if it throws, unwind to bb2)
711*0b57cec5SDimitry Andric   // bb1:
712*0b57cec5SDimitry Andric   //   call @bar (if it throws, unwind to bb3)
713*0b57cec5SDimitry Andric   // bb2 (ehpad):
714*0b57cec5SDimitry Andric   //   catch
715*0b57cec5SDimitry Andric   //   ...
716*0b57cec5SDimitry Andric   // bb3 (ehpad)
717*0b57cec5SDimitry Andric   //   catch
718*0b57cec5SDimitry Andric   //   handler body
719*0b57cec5SDimitry Andric   //
720*0b57cec5SDimitry Andric   // And the CFG is sorted in this order. Then after placing TRY markers, it
721*0b57cec5SDimitry Andric   // will look like: (BB markers are omitted)
722*0b57cec5SDimitry Andric   // try $label1
723*0b57cec5SDimitry Andric   //   try
724*0b57cec5SDimitry Andric   //     call @foo
725*0b57cec5SDimitry Andric   //     call @bar   (if it throws, unwind to bb3)
726*0b57cec5SDimitry Andric   //   catch         <- ehpad (bb2)
727*0b57cec5SDimitry Andric   //     ...
728*0b57cec5SDimitry Andric   //   end_try
729*0b57cec5SDimitry Andric   // catch           <- ehpad (bb3)
730*0b57cec5SDimitry Andric   //   handler body
731*0b57cec5SDimitry Andric   // end_try
732*0b57cec5SDimitry Andric   //
733*0b57cec5SDimitry Andric   // Now if bar() throws, it is going to end up ip in bb2, not bb3, where it
734*0b57cec5SDimitry Andric   // is supposed to end up. We solve this problem by
735*0b57cec5SDimitry Andric   // a. Split the target unwind EH pad (here bb3) so that the handler body is
736*0b57cec5SDimitry Andric   //    right after 'end_try', which means we extract the handler body out of
737*0b57cec5SDimitry Andric   //    the catch block. We do this because this handler body should be
738*0b57cec5SDimitry Andric   //    somewhere branch-eable from the inner scope.
739*0b57cec5SDimitry Andric   // b. Wrap the call that has an incorrect unwind destination ('call @bar'
740*0b57cec5SDimitry Andric   //    here) with a nested try/catch/end_try scope, and within the new catch
741*0b57cec5SDimitry Andric   //    block, branches to the handler body.
742*0b57cec5SDimitry Andric   // c. Place a branch after the newly inserted nested end_try so it can bypass
743*0b57cec5SDimitry Andric   //    the handler body, which is now outside of a catch block.
744*0b57cec5SDimitry Andric   //
745*0b57cec5SDimitry Andric   // The result will like as follows. (new: a) means this instruction is newly
746*0b57cec5SDimitry Andric   // created in the process of doing 'a' above.
747*0b57cec5SDimitry Andric   //
748*0b57cec5SDimitry Andric   // block $label0                 (new: placeBlockMarker)
749*0b57cec5SDimitry Andric   //   try $label1
750*0b57cec5SDimitry Andric   //     try
751*0b57cec5SDimitry Andric   //       call @foo
752*0b57cec5SDimitry Andric   //       try                     (new: b)
753*0b57cec5SDimitry Andric   //         call @bar
754*0b57cec5SDimitry Andric   //       catch                   (new: b)
755*0b57cec5SDimitry Andric   //         local.set n / drop    (new: b)
756*0b57cec5SDimitry Andric   //         br $label1            (new: b)
757*0b57cec5SDimitry Andric   //       end_try                 (new: b)
758*0b57cec5SDimitry Andric   //     catch                     <- ehpad (bb2)
759*0b57cec5SDimitry Andric   //     end_try
760*0b57cec5SDimitry Andric   //     br $label0                (new: c)
761*0b57cec5SDimitry Andric   //   catch                       <- ehpad (bb3)
762*0b57cec5SDimitry Andric   //   end_try                     (hoisted: a)
763*0b57cec5SDimitry Andric   //   handler body
764*0b57cec5SDimitry Andric   // end_block                     (new: placeBlockMarker)
765*0b57cec5SDimitry Andric   //
766*0b57cec5SDimitry Andric   // Note that the new wrapping block/end_block will be generated later in
767*0b57cec5SDimitry Andric   // placeBlockMarker.
768*0b57cec5SDimitry Andric   //
769*0b57cec5SDimitry Andric   // TODO Currently local.set and local.gets are generated to move exnref value
770*0b57cec5SDimitry Andric   // created by catches. That's because we don't support yielding values from a
771*0b57cec5SDimitry Andric   // block in LLVM machine IR yet, even though it is supported by wasm. Delete
772*0b57cec5SDimitry Andric   // unnecessary local.get/local.sets once yielding values from a block is
773*0b57cec5SDimitry Andric   // supported. The full EH spec requires multi-value support to do this, but
774*0b57cec5SDimitry Andric   // for C++ we don't yet need it because we only throw a single i32.
775*0b57cec5SDimitry Andric   //
776*0b57cec5SDimitry Andric   // ---
777*0b57cec5SDimitry Andric   // 2. The same as 1, but in this case an instruction unwinds to a caller
778*0b57cec5SDimitry Andric   //    function and not another EH pad.
779*0b57cec5SDimitry Andric   //
780*0b57cec5SDimitry Andric   // Example: we have the following CFG:
781*0b57cec5SDimitry Andric   // bb0:
782*0b57cec5SDimitry Andric   //   call @foo (if it throws, unwind to bb2)
783*0b57cec5SDimitry Andric   // bb1:
784*0b57cec5SDimitry Andric   //   call @bar (if it throws, unwind to caller)
785*0b57cec5SDimitry Andric   // bb2 (ehpad):
786*0b57cec5SDimitry Andric   //   catch
787*0b57cec5SDimitry Andric   //   ...
788*0b57cec5SDimitry Andric   //
789*0b57cec5SDimitry Andric   // And the CFG is sorted in this order. Then after placing TRY markers, it
790*0b57cec5SDimitry Andric   // will look like:
791*0b57cec5SDimitry Andric   // try
792*0b57cec5SDimitry Andric   //   call @foo
793*0b57cec5SDimitry Andric   //   call @bar   (if it throws, unwind to caller)
794*0b57cec5SDimitry Andric   // catch         <- ehpad (bb2)
795*0b57cec5SDimitry Andric   //   ...
796*0b57cec5SDimitry Andric   // end_try
797*0b57cec5SDimitry Andric   //
798*0b57cec5SDimitry Andric   // Now if bar() throws, it is going to end up ip in bb2, when it is supposed
799*0b57cec5SDimitry Andric   // throw up to the caller.
800*0b57cec5SDimitry Andric   // We solve this problem by
801*0b57cec5SDimitry Andric   // a. Create a new 'appendix' BB at the end of the function and put a single
802*0b57cec5SDimitry Andric   //    'rethrow' instruction (+ local.get) in there.
803*0b57cec5SDimitry Andric   // b. Wrap the call that has an incorrect unwind destination ('call @bar'
804*0b57cec5SDimitry Andric   //    here) with a nested try/catch/end_try scope, and within the new catch
805*0b57cec5SDimitry Andric   //    block, branches to the new appendix block.
806*0b57cec5SDimitry Andric   //
807*0b57cec5SDimitry Andric   // block $label0          (new: placeBlockMarker)
808*0b57cec5SDimitry Andric   //   try
809*0b57cec5SDimitry Andric   //     call @foo
810*0b57cec5SDimitry Andric   //     try                (new: b)
811*0b57cec5SDimitry Andric   //       call @bar
812*0b57cec5SDimitry Andric   //     catch              (new: b)
813*0b57cec5SDimitry Andric   //       local.set n      (new: b)
814*0b57cec5SDimitry Andric   //       br $label0       (new: b)
815*0b57cec5SDimitry Andric   //     end_try            (new: b)
816*0b57cec5SDimitry Andric   //   catch                <- ehpad (bb2)
817*0b57cec5SDimitry Andric   //     ...
818*0b57cec5SDimitry Andric   //   end_try
819*0b57cec5SDimitry Andric   // ...
820*0b57cec5SDimitry Andric   // end_block              (new: placeBlockMarker)
821*0b57cec5SDimitry Andric   // local.get n            (new: a)  <- appendix block
822*0b57cec5SDimitry Andric   // rethrow                (new: a)
823*0b57cec5SDimitry Andric   //
824*0b57cec5SDimitry Andric   // In case there are multiple calls in a BB that may throw to the caller, they
825*0b57cec5SDimitry Andric   // can be wrapped together in one nested try scope. (In 1, this couldn't
826*0b57cec5SDimitry Andric   // happen, because may-throwing instruction there had an unwind destination,
827*0b57cec5SDimitry Andric   // i.e., it was an invoke before, and there could be only one invoke within a
828*0b57cec5SDimitry Andric   // BB.)
829*0b57cec5SDimitry Andric 
830*0b57cec5SDimitry Andric   SmallVector<const MachineBasicBlock *, 8> EHPadStack;
831*0b57cec5SDimitry Andric   // Range of intructions to be wrapped in a new nested try/catch
832*0b57cec5SDimitry Andric   using TryRange = std::pair<MachineInstr *, MachineInstr *>;
833*0b57cec5SDimitry Andric   // In original CFG, <unwind destionation BB, a vector of try ranges>
834*0b57cec5SDimitry Andric   DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> UnwindDestToTryRanges;
835*0b57cec5SDimitry Andric   // In new CFG, <destination to branch to, a vector of try ranges>
836*0b57cec5SDimitry Andric   DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> BrDestToTryRanges;
837*0b57cec5SDimitry Andric   // In new CFG, <destination to branch to, register containing exnref>
838*0b57cec5SDimitry Andric   DenseMap<MachineBasicBlock *, unsigned> BrDestToExnReg;
839*0b57cec5SDimitry Andric 
840*0b57cec5SDimitry Andric   // Gather possibly throwing calls (i.e., previously invokes) whose current
841*0b57cec5SDimitry Andric   // unwind destination is not the same as the original CFG.
842*0b57cec5SDimitry Andric   for (auto &MBB : reverse(MF)) {
843*0b57cec5SDimitry Andric     bool SeenThrowableInstInBB = false;
844*0b57cec5SDimitry Andric     for (auto &MI : reverse(MBB)) {
845*0b57cec5SDimitry Andric       if (MI.getOpcode() == WebAssembly::TRY)
846*0b57cec5SDimitry Andric         EHPadStack.pop_back();
847*0b57cec5SDimitry Andric       else if (MI.getOpcode() == WebAssembly::CATCH)
848*0b57cec5SDimitry Andric         EHPadStack.push_back(MI.getParent());
849*0b57cec5SDimitry Andric 
850*0b57cec5SDimitry Andric       // In this loop we only gather calls that have an EH pad to unwind. So
851*0b57cec5SDimitry Andric       // there will be at most 1 such call (= invoke) in a BB, so after we've
852*0b57cec5SDimitry Andric       // seen one, we can skip the rest of BB. Also if MBB has no EH pad
853*0b57cec5SDimitry Andric       // successor or MI does not throw, this is not an invoke.
854*0b57cec5SDimitry Andric       if (SeenThrowableInstInBB || !MBB.hasEHPadSuccessor() ||
855*0b57cec5SDimitry Andric           !WebAssembly::mayThrow(MI))
856*0b57cec5SDimitry Andric         continue;
857*0b57cec5SDimitry Andric       SeenThrowableInstInBB = true;
858*0b57cec5SDimitry Andric 
859*0b57cec5SDimitry Andric       // If the EH pad on the stack top is where this instruction should unwind
860*0b57cec5SDimitry Andric       // next, we're good.
861*0b57cec5SDimitry Andric       MachineBasicBlock *UnwindDest = nullptr;
862*0b57cec5SDimitry Andric       for (auto *Succ : MBB.successors()) {
863*0b57cec5SDimitry Andric         if (Succ->isEHPad()) {
864*0b57cec5SDimitry Andric           UnwindDest = Succ;
865*0b57cec5SDimitry Andric           break;
866*0b57cec5SDimitry Andric         }
867*0b57cec5SDimitry Andric       }
868*0b57cec5SDimitry Andric       if (EHPadStack.back() == UnwindDest)
869*0b57cec5SDimitry Andric         continue;
870*0b57cec5SDimitry Andric 
871*0b57cec5SDimitry Andric       // If not, record the range.
872*0b57cec5SDimitry Andric       UnwindDestToTryRanges[UnwindDest].push_back(TryRange(&MI, &MI));
873*0b57cec5SDimitry Andric     }
874*0b57cec5SDimitry Andric   }
875*0b57cec5SDimitry Andric 
876*0b57cec5SDimitry Andric   assert(EHPadStack.empty());
877*0b57cec5SDimitry Andric 
878*0b57cec5SDimitry Andric   // Gather possibly throwing calls that are supposed to unwind up to the caller
879*0b57cec5SDimitry Andric   // if they throw, but currently unwind to an incorrect destination. Unlike the
880*0b57cec5SDimitry Andric   // loop above, there can be multiple calls within a BB that unwind to the
881*0b57cec5SDimitry Andric   // caller, which we should group together in a range.
882*0b57cec5SDimitry Andric   bool NeedAppendixBlock = false;
883*0b57cec5SDimitry Andric   for (auto &MBB : reverse(MF)) {
884*0b57cec5SDimitry Andric     MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; // inclusive
885*0b57cec5SDimitry Andric     for (auto &MI : reverse(MBB)) {
886*0b57cec5SDimitry Andric       if (MI.getOpcode() == WebAssembly::TRY)
887*0b57cec5SDimitry Andric         EHPadStack.pop_back();
888*0b57cec5SDimitry Andric       else if (MI.getOpcode() == WebAssembly::CATCH)
889*0b57cec5SDimitry Andric         EHPadStack.push_back(MI.getParent());
890*0b57cec5SDimitry Andric 
891*0b57cec5SDimitry Andric       // If MBB has an EH pad successor, this inst does not unwind to caller.
892*0b57cec5SDimitry Andric       if (MBB.hasEHPadSuccessor())
893*0b57cec5SDimitry Andric         continue;
894*0b57cec5SDimitry Andric 
895*0b57cec5SDimitry Andric       // We wrap up the current range when we see a marker even if we haven't
896*0b57cec5SDimitry Andric       // finished a BB.
897*0b57cec5SDimitry Andric       if (RangeEnd && WebAssembly::isMarker(MI.getOpcode())) {
898*0b57cec5SDimitry Andric         NeedAppendixBlock = true;
899*0b57cec5SDimitry Andric         // Record the range. nullptr here means the unwind destination is the
900*0b57cec5SDimitry Andric         // caller.
901*0b57cec5SDimitry Andric         UnwindDestToTryRanges[nullptr].push_back(
902*0b57cec5SDimitry Andric             TryRange(RangeBegin, RangeEnd));
903*0b57cec5SDimitry Andric         RangeBegin = RangeEnd = nullptr; // Reset range pointers
904*0b57cec5SDimitry Andric       }
905*0b57cec5SDimitry Andric 
906*0b57cec5SDimitry Andric       // If EHPadStack is empty, that means it is correctly unwind to caller if
907*0b57cec5SDimitry Andric       // it throws, so we're good. If MI does not throw, we're good too.
908*0b57cec5SDimitry Andric       if (EHPadStack.empty() || !WebAssembly::mayThrow(MI))
909*0b57cec5SDimitry Andric         continue;
910*0b57cec5SDimitry Andric 
911*0b57cec5SDimitry Andric       // We found an instruction that unwinds to the caller but currently has an
912*0b57cec5SDimitry Andric       // incorrect unwind destination. Create a new range or increment the
913*0b57cec5SDimitry Andric       // currently existing range.
914*0b57cec5SDimitry Andric       if (!RangeEnd)
915*0b57cec5SDimitry Andric         RangeBegin = RangeEnd = &MI;
916*0b57cec5SDimitry Andric       else
917*0b57cec5SDimitry Andric         RangeBegin = &MI;
918*0b57cec5SDimitry Andric     }
919*0b57cec5SDimitry Andric 
920*0b57cec5SDimitry Andric     if (RangeEnd) {
921*0b57cec5SDimitry Andric       NeedAppendixBlock = true;
922*0b57cec5SDimitry Andric       // Record the range. nullptr here means the unwind destination is the
923*0b57cec5SDimitry Andric       // caller.
924*0b57cec5SDimitry Andric       UnwindDestToTryRanges[nullptr].push_back(TryRange(RangeBegin, RangeEnd));
925*0b57cec5SDimitry Andric       RangeBegin = RangeEnd = nullptr; // Reset range pointers
926*0b57cec5SDimitry Andric     }
927*0b57cec5SDimitry Andric   }
928*0b57cec5SDimitry Andric 
929*0b57cec5SDimitry Andric   assert(EHPadStack.empty());
930*0b57cec5SDimitry Andric   // We don't have any unwind destination mismatches to resolve.
931*0b57cec5SDimitry Andric   if (UnwindDestToTryRanges.empty())
932*0b57cec5SDimitry Andric     return false;
933*0b57cec5SDimitry Andric 
934*0b57cec5SDimitry Andric   // If we found instructions that should unwind to the caller but currently
935*0b57cec5SDimitry Andric   // have incorrect unwind destination, we create an appendix block at the end
936*0b57cec5SDimitry Andric   // of the function with a local.get and a rethrow instruction.
937*0b57cec5SDimitry Andric   if (NeedAppendixBlock) {
938*0b57cec5SDimitry Andric     auto *AppendixBB = getAppendixBlock(MF);
939*0b57cec5SDimitry Andric     unsigned ExnReg = MRI.createVirtualRegister(&WebAssembly::EXNREFRegClass);
940*0b57cec5SDimitry Andric     BuildMI(AppendixBB, DebugLoc(), TII.get(WebAssembly::RETHROW))
941*0b57cec5SDimitry Andric         .addReg(ExnReg);
942*0b57cec5SDimitry Andric     // These instruction ranges should branch to this appendix BB.
943*0b57cec5SDimitry Andric     for (auto Range : UnwindDestToTryRanges[nullptr])
944*0b57cec5SDimitry Andric       BrDestToTryRanges[AppendixBB].push_back(Range);
945*0b57cec5SDimitry Andric     BrDestToExnReg[AppendixBB] = ExnReg;
946*0b57cec5SDimitry Andric   }
947*0b57cec5SDimitry Andric 
948*0b57cec5SDimitry Andric   // We loop through unwind destination EH pads that are targeted from some
949*0b57cec5SDimitry Andric   // inner scopes. Because these EH pads are destination of more than one scope
950*0b57cec5SDimitry Andric   // now, we split them so that the handler body is after 'end_try'.
951*0b57cec5SDimitry Andric   // - Before
952*0b57cec5SDimitry Andric   // ehpad:
953*0b57cec5SDimitry Andric   //   catch
954*0b57cec5SDimitry Andric   //   local.set n / drop
955*0b57cec5SDimitry Andric   //   handler body
956*0b57cec5SDimitry Andric   // ...
957*0b57cec5SDimitry Andric   // cont:
958*0b57cec5SDimitry Andric   //   end_try
959*0b57cec5SDimitry Andric   //
960*0b57cec5SDimitry Andric   // - After
961*0b57cec5SDimitry Andric   // ehpad:
962*0b57cec5SDimitry Andric   //   catch
963*0b57cec5SDimitry Andric   //   local.set n / drop
964*0b57cec5SDimitry Andric   // brdest:               (new)
965*0b57cec5SDimitry Andric   //   end_try             (hoisted from 'cont' BB)
966*0b57cec5SDimitry Andric   //   handler body        (taken from 'ehpad')
967*0b57cec5SDimitry Andric   // ...
968*0b57cec5SDimitry Andric   // cont:
969*0b57cec5SDimitry Andric   for (auto &P : UnwindDestToTryRanges) {
970*0b57cec5SDimitry Andric     NumUnwindMismatches++;
971*0b57cec5SDimitry Andric 
972*0b57cec5SDimitry Andric     // This means the destination is the appendix BB, which was separately
973*0b57cec5SDimitry Andric     // handled above.
974*0b57cec5SDimitry Andric     if (!P.first)
975*0b57cec5SDimitry Andric       continue;
976*0b57cec5SDimitry Andric 
977*0b57cec5SDimitry Andric     MachineBasicBlock *EHPad = P.first;
978*0b57cec5SDimitry Andric 
979*0b57cec5SDimitry Andric     // Find 'catch' and 'local.set' or 'drop' instruction that follows the
980*0b57cec5SDimitry Andric     // 'catch'. If -wasm-disable-explicit-locals is not set, 'catch' should be
981*0b57cec5SDimitry Andric     // always followed by either 'local.set' or a 'drop', because 'br_on_exn' is
982*0b57cec5SDimitry Andric     // generated after 'catch' in LateEHPrepare and we don't support blocks
983*0b57cec5SDimitry Andric     // taking values yet.
984*0b57cec5SDimitry Andric     MachineInstr *Catch = nullptr;
985*0b57cec5SDimitry Andric     unsigned ExnReg = 0;
986*0b57cec5SDimitry Andric     for (auto &MI : *EHPad) {
987*0b57cec5SDimitry Andric       switch (MI.getOpcode()) {
988*0b57cec5SDimitry Andric       case WebAssembly::CATCH:
989*0b57cec5SDimitry Andric         Catch = &MI;
990*0b57cec5SDimitry Andric         ExnReg = Catch->getOperand(0).getReg();
991*0b57cec5SDimitry Andric         break;
992*0b57cec5SDimitry Andric       }
993*0b57cec5SDimitry Andric     }
994*0b57cec5SDimitry Andric     assert(Catch && "EH pad does not have a catch");
995*0b57cec5SDimitry Andric     assert(ExnReg != 0 && "Invalid register");
996*0b57cec5SDimitry Andric 
997*0b57cec5SDimitry Andric     auto SplitPos = std::next(Catch->getIterator());
998*0b57cec5SDimitry Andric 
999*0b57cec5SDimitry Andric     // Create a new BB that's gonna be the destination for branches from the
1000*0b57cec5SDimitry Andric     // inner mismatched scope.
1001*0b57cec5SDimitry Andric     MachineInstr *BeginTry = EHPadToTry[EHPad];
1002*0b57cec5SDimitry Andric     MachineInstr *EndTry = BeginToEnd[BeginTry];
1003*0b57cec5SDimitry Andric     MachineBasicBlock *Cont = EndTry->getParent();
1004*0b57cec5SDimitry Andric     auto *BrDest = MF.CreateMachineBasicBlock();
1005*0b57cec5SDimitry Andric     MF.insert(std::next(EHPad->getIterator()), BrDest);
1006*0b57cec5SDimitry Andric     // Hoist up the existing 'end_try'.
1007*0b57cec5SDimitry Andric     BrDest->insert(BrDest->end(), EndTry->removeFromParent());
1008*0b57cec5SDimitry Andric     // Take out the handler body from EH pad to the new branch destination BB.
1009*0b57cec5SDimitry Andric     BrDest->splice(BrDest->end(), EHPad, SplitPos, EHPad->end());
1010*0b57cec5SDimitry Andric     // Fix predecessor-successor relationship.
1011*0b57cec5SDimitry Andric     BrDest->transferSuccessors(EHPad);
1012*0b57cec5SDimitry Andric     EHPad->addSuccessor(BrDest);
1013*0b57cec5SDimitry Andric 
1014*0b57cec5SDimitry Andric     // All try ranges that were supposed to unwind to this EH pad now have to
1015*0b57cec5SDimitry Andric     // branch to this new branch dest BB.
1016*0b57cec5SDimitry Andric     for (auto Range : UnwindDestToTryRanges[EHPad])
1017*0b57cec5SDimitry Andric       BrDestToTryRanges[BrDest].push_back(Range);
1018*0b57cec5SDimitry Andric     BrDestToExnReg[BrDest] = ExnReg;
1019*0b57cec5SDimitry Andric 
1020*0b57cec5SDimitry Andric     // In case we fall through to the continuation BB after the catch block, we
1021*0b57cec5SDimitry Andric     // now have to add a branch to it.
1022*0b57cec5SDimitry Andric     // - Before
1023*0b57cec5SDimitry Andric     // try
1024*0b57cec5SDimitry Andric     //   ...
1025*0b57cec5SDimitry Andric     //   (falls through to 'cont')
1026*0b57cec5SDimitry Andric     // catch
1027*0b57cec5SDimitry Andric     //   handler body
1028*0b57cec5SDimitry Andric     // end
1029*0b57cec5SDimitry Andric     //               <-- cont
1030*0b57cec5SDimitry Andric     //
1031*0b57cec5SDimitry Andric     // - After
1032*0b57cec5SDimitry Andric     // try
1033*0b57cec5SDimitry Andric     //   ...
1034*0b57cec5SDimitry Andric     //   br %cont    (new)
1035*0b57cec5SDimitry Andric     // catch
1036*0b57cec5SDimitry Andric     // end
1037*0b57cec5SDimitry Andric     // handler body
1038*0b57cec5SDimitry Andric     //               <-- cont
1039*0b57cec5SDimitry Andric     MachineBasicBlock *EHPadLayoutPred = &*std::prev(EHPad->getIterator());
1040*0b57cec5SDimitry Andric     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1041*0b57cec5SDimitry Andric     SmallVector<MachineOperand, 4> Cond;
1042*0b57cec5SDimitry Andric     bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond);
1043*0b57cec5SDimitry Andric     if (Analyzable && !TBB && !FBB) {
1044*0b57cec5SDimitry Andric       DebugLoc DL = EHPadLayoutPred->empty()
1045*0b57cec5SDimitry Andric                         ? DebugLoc()
1046*0b57cec5SDimitry Andric                         : EHPadLayoutPred->rbegin()->getDebugLoc();
1047*0b57cec5SDimitry Andric       BuildMI(EHPadLayoutPred, DL, TII.get(WebAssembly::BR)).addMBB(Cont);
1048*0b57cec5SDimitry Andric     }
1049*0b57cec5SDimitry Andric   }
1050*0b57cec5SDimitry Andric 
1051*0b57cec5SDimitry Andric   // For possibly throwing calls whose unwind destinations are currently
1052*0b57cec5SDimitry Andric   // incorrect because of CFG linearization, we wrap them with a nested
1053*0b57cec5SDimitry Andric   // try/catch/end_try, and within the new catch block, we branch to the correct
1054*0b57cec5SDimitry Andric   // handler.
1055*0b57cec5SDimitry Andric   // - Before
1056*0b57cec5SDimitry Andric   // mbb:
1057*0b57cec5SDimitry Andric   //   call @foo       <- Unwind destination mismatch!
1058*0b57cec5SDimitry Andric   // ehpad:
1059*0b57cec5SDimitry Andric   //   ...
1060*0b57cec5SDimitry Andric   //
1061*0b57cec5SDimitry Andric   // - After
1062*0b57cec5SDimitry Andric   // mbb:
1063*0b57cec5SDimitry Andric   //   try                (new)
1064*0b57cec5SDimitry Andric   //   call @foo
1065*0b57cec5SDimitry Andric   // nested-ehpad:        (new)
1066*0b57cec5SDimitry Andric   //   catch              (new)
1067*0b57cec5SDimitry Andric   //   local.set n / drop (new)
1068*0b57cec5SDimitry Andric   //   br %brdest         (new)
1069*0b57cec5SDimitry Andric   // nested-end:          (new)
1070*0b57cec5SDimitry Andric   //   end_try            (new)
1071*0b57cec5SDimitry Andric   // ehpad:
1072*0b57cec5SDimitry Andric   //   ...
1073*0b57cec5SDimitry Andric   for (auto &P : BrDestToTryRanges) {
1074*0b57cec5SDimitry Andric     MachineBasicBlock *BrDest = P.first;
1075*0b57cec5SDimitry Andric     auto &TryRanges = P.second;
1076*0b57cec5SDimitry Andric     unsigned ExnReg = BrDestToExnReg[BrDest];
1077*0b57cec5SDimitry Andric 
1078*0b57cec5SDimitry Andric     for (auto Range : TryRanges) {
1079*0b57cec5SDimitry Andric       MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr;
1080*0b57cec5SDimitry Andric       std::tie(RangeBegin, RangeEnd) = Range;
1081*0b57cec5SDimitry Andric       auto *MBB = RangeBegin->getParent();
1082*0b57cec5SDimitry Andric 
1083*0b57cec5SDimitry Andric       // Include possible EH_LABELs in the range
1084*0b57cec5SDimitry Andric       if (RangeBegin->getIterator() != MBB->begin() &&
1085*0b57cec5SDimitry Andric           std::prev(RangeBegin->getIterator())->isEHLabel())
1086*0b57cec5SDimitry Andric         RangeBegin = &*std::prev(RangeBegin->getIterator());
1087*0b57cec5SDimitry Andric       if (std::next(RangeEnd->getIterator()) != MBB->end() &&
1088*0b57cec5SDimitry Andric           std::next(RangeEnd->getIterator())->isEHLabel())
1089*0b57cec5SDimitry Andric         RangeEnd = &*std::next(RangeEnd->getIterator());
1090*0b57cec5SDimitry Andric 
1091*0b57cec5SDimitry Andric       MachineBasicBlock *EHPad = nullptr;
1092*0b57cec5SDimitry Andric       for (auto *Succ : MBB->successors()) {
1093*0b57cec5SDimitry Andric         if (Succ->isEHPad()) {
1094*0b57cec5SDimitry Andric           EHPad = Succ;
1095*0b57cec5SDimitry Andric           break;
1096*0b57cec5SDimitry Andric         }
1097*0b57cec5SDimitry Andric       }
1098*0b57cec5SDimitry Andric 
1099*0b57cec5SDimitry Andric       // Create the nested try instruction.
1100*0b57cec5SDimitry Andric       MachineInstr *NestedTry =
1101*0b57cec5SDimitry Andric           BuildMI(*MBB, *RangeBegin, RangeBegin->getDebugLoc(),
1102*0b57cec5SDimitry Andric                   TII.get(WebAssembly::TRY))
1103*0b57cec5SDimitry Andric               .addImm(int64_t(WebAssembly::ExprType::Void));
1104*0b57cec5SDimitry Andric 
1105*0b57cec5SDimitry Andric       // Create the nested EH pad and fill instructions in.
1106*0b57cec5SDimitry Andric       MachineBasicBlock *NestedEHPad = MF.CreateMachineBasicBlock();
1107*0b57cec5SDimitry Andric       MF.insert(std::next(MBB->getIterator()), NestedEHPad);
1108*0b57cec5SDimitry Andric       NestedEHPad->setIsEHPad();
1109*0b57cec5SDimitry Andric       NestedEHPad->setIsEHScopeEntry();
1110*0b57cec5SDimitry Andric       BuildMI(NestedEHPad, RangeEnd->getDebugLoc(), TII.get(WebAssembly::CATCH),
1111*0b57cec5SDimitry Andric               ExnReg);
1112*0b57cec5SDimitry Andric       BuildMI(NestedEHPad, RangeEnd->getDebugLoc(), TII.get(WebAssembly::BR))
1113*0b57cec5SDimitry Andric           .addMBB(BrDest);
1114*0b57cec5SDimitry Andric 
1115*0b57cec5SDimitry Andric       // Create the nested continuation BB and end_try instruction.
1116*0b57cec5SDimitry Andric       MachineBasicBlock *NestedCont = MF.CreateMachineBasicBlock();
1117*0b57cec5SDimitry Andric       MF.insert(std::next(NestedEHPad->getIterator()), NestedCont);
1118*0b57cec5SDimitry Andric       MachineInstr *NestedEndTry =
1119*0b57cec5SDimitry Andric           BuildMI(*NestedCont, NestedCont->begin(), RangeEnd->getDebugLoc(),
1120*0b57cec5SDimitry Andric                   TII.get(WebAssembly::END_TRY));
1121*0b57cec5SDimitry Andric       // In case MBB has more instructions after the try range, move them to the
1122*0b57cec5SDimitry Andric       // new nested continuation BB.
1123*0b57cec5SDimitry Andric       NestedCont->splice(NestedCont->end(), MBB,
1124*0b57cec5SDimitry Andric                          std::next(RangeEnd->getIterator()), MBB->end());
1125*0b57cec5SDimitry Andric       registerTryScope(NestedTry, NestedEndTry, NestedEHPad);
1126*0b57cec5SDimitry Andric 
1127*0b57cec5SDimitry Andric       // Fix predecessor-successor relationship.
1128*0b57cec5SDimitry Andric       NestedCont->transferSuccessors(MBB);
1129*0b57cec5SDimitry Andric       if (EHPad)
1130*0b57cec5SDimitry Andric         NestedCont->removeSuccessor(EHPad);
1131*0b57cec5SDimitry Andric       MBB->addSuccessor(NestedEHPad);
1132*0b57cec5SDimitry Andric       MBB->addSuccessor(NestedCont);
1133*0b57cec5SDimitry Andric       NestedEHPad->addSuccessor(BrDest);
1134*0b57cec5SDimitry Andric     }
1135*0b57cec5SDimitry Andric   }
1136*0b57cec5SDimitry Andric 
1137*0b57cec5SDimitry Andric   // Renumber BBs and recalculate ScopeTop info because new BBs might have been
1138*0b57cec5SDimitry Andric   // created and inserted above.
1139*0b57cec5SDimitry Andric   MF.RenumberBlocks();
1140*0b57cec5SDimitry Andric   ScopeTops.clear();
1141*0b57cec5SDimitry Andric   ScopeTops.resize(MF.getNumBlockIDs());
1142*0b57cec5SDimitry Andric   for (auto &MBB : reverse(MF)) {
1143*0b57cec5SDimitry Andric     for (auto &MI : reverse(MBB)) {
1144*0b57cec5SDimitry Andric       if (ScopeTops[MBB.getNumber()])
1145*0b57cec5SDimitry Andric         break;
1146*0b57cec5SDimitry Andric       switch (MI.getOpcode()) {
1147*0b57cec5SDimitry Andric       case WebAssembly::END_BLOCK:
1148*0b57cec5SDimitry Andric       case WebAssembly::END_LOOP:
1149*0b57cec5SDimitry Andric       case WebAssembly::END_TRY:
1150*0b57cec5SDimitry Andric         ScopeTops[MBB.getNumber()] = EndToBegin[&MI]->getParent();
1151*0b57cec5SDimitry Andric         break;
1152*0b57cec5SDimitry Andric       case WebAssembly::CATCH:
1153*0b57cec5SDimitry Andric         ScopeTops[MBB.getNumber()] = EHPadToTry[&MBB]->getParent();
1154*0b57cec5SDimitry Andric         break;
1155*0b57cec5SDimitry Andric       }
1156*0b57cec5SDimitry Andric     }
1157*0b57cec5SDimitry Andric   }
1158*0b57cec5SDimitry Andric 
1159*0b57cec5SDimitry Andric   // Recompute the dominator tree.
1160*0b57cec5SDimitry Andric   getAnalysis<MachineDominatorTree>().runOnMachineFunction(MF);
1161*0b57cec5SDimitry Andric 
1162*0b57cec5SDimitry Andric   // Place block markers for newly added branches.
1163*0b57cec5SDimitry Andric   SmallVector <MachineBasicBlock *, 8> BrDests;
1164*0b57cec5SDimitry Andric   for (auto &P : BrDestToTryRanges)
1165*0b57cec5SDimitry Andric     BrDests.push_back(P.first);
1166*0b57cec5SDimitry Andric   llvm::sort(BrDests,
1167*0b57cec5SDimitry Andric              [&](const MachineBasicBlock *A, const MachineBasicBlock *B) {
1168*0b57cec5SDimitry Andric                auto ANum = A->getNumber();
1169*0b57cec5SDimitry Andric                auto BNum = B->getNumber();
1170*0b57cec5SDimitry Andric                return ANum < BNum;
1171*0b57cec5SDimitry Andric              });
1172*0b57cec5SDimitry Andric   for (auto *Dest : BrDests)
1173*0b57cec5SDimitry Andric     placeBlockMarker(*Dest);
1174*0b57cec5SDimitry Andric 
1175*0b57cec5SDimitry Andric   return true;
1176*0b57cec5SDimitry Andric }
1177*0b57cec5SDimitry Andric 
1178*0b57cec5SDimitry Andric static unsigned
1179*0b57cec5SDimitry Andric getDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
1180*0b57cec5SDimitry Andric          const MachineBasicBlock *MBB) {
1181*0b57cec5SDimitry Andric   unsigned Depth = 0;
1182*0b57cec5SDimitry Andric   for (auto X : reverse(Stack)) {
1183*0b57cec5SDimitry Andric     if (X == MBB)
1184*0b57cec5SDimitry Andric       break;
1185*0b57cec5SDimitry Andric     ++Depth;
1186*0b57cec5SDimitry Andric   }
1187*0b57cec5SDimitry Andric   assert(Depth < Stack.size() && "Branch destination should be in scope");
1188*0b57cec5SDimitry Andric   return Depth;
1189*0b57cec5SDimitry Andric }
1190*0b57cec5SDimitry Andric 
1191*0b57cec5SDimitry Andric /// In normal assembly languages, when the end of a function is unreachable,
1192*0b57cec5SDimitry Andric /// because the function ends in an infinite loop or a noreturn call or similar,
1193*0b57cec5SDimitry Andric /// it isn't necessary to worry about the function return type at the end of
1194*0b57cec5SDimitry Andric /// the function, because it's never reached. However, in WebAssembly, blocks
1195*0b57cec5SDimitry Andric /// that end at the function end need to have a return type signature that
1196*0b57cec5SDimitry Andric /// matches the function signature, even though it's unreachable. This function
1197*0b57cec5SDimitry Andric /// checks for such cases and fixes up the signatures.
1198*0b57cec5SDimitry Andric void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) {
1199*0b57cec5SDimitry Andric   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
1200*0b57cec5SDimitry Andric   assert(MFI.getResults().size() <= 1);
1201*0b57cec5SDimitry Andric 
1202*0b57cec5SDimitry Andric   if (MFI.getResults().empty())
1203*0b57cec5SDimitry Andric     return;
1204*0b57cec5SDimitry Andric 
1205*0b57cec5SDimitry Andric   WebAssembly::ExprType RetType;
1206*0b57cec5SDimitry Andric   switch (MFI.getResults().front().SimpleTy) {
1207*0b57cec5SDimitry Andric   case MVT::i32:
1208*0b57cec5SDimitry Andric     RetType = WebAssembly::ExprType::I32;
1209*0b57cec5SDimitry Andric     break;
1210*0b57cec5SDimitry Andric   case MVT::i64:
1211*0b57cec5SDimitry Andric     RetType = WebAssembly::ExprType::I64;
1212*0b57cec5SDimitry Andric     break;
1213*0b57cec5SDimitry Andric   case MVT::f32:
1214*0b57cec5SDimitry Andric     RetType = WebAssembly::ExprType::F32;
1215*0b57cec5SDimitry Andric     break;
1216*0b57cec5SDimitry Andric   case MVT::f64:
1217*0b57cec5SDimitry Andric     RetType = WebAssembly::ExprType::F64;
1218*0b57cec5SDimitry Andric     break;
1219*0b57cec5SDimitry Andric   case MVT::v16i8:
1220*0b57cec5SDimitry Andric   case MVT::v8i16:
1221*0b57cec5SDimitry Andric   case MVT::v4i32:
1222*0b57cec5SDimitry Andric   case MVT::v2i64:
1223*0b57cec5SDimitry Andric   case MVT::v4f32:
1224*0b57cec5SDimitry Andric   case MVT::v2f64:
1225*0b57cec5SDimitry Andric     RetType = WebAssembly::ExprType::V128;
1226*0b57cec5SDimitry Andric     break;
1227*0b57cec5SDimitry Andric   case MVT::exnref:
1228*0b57cec5SDimitry Andric     RetType = WebAssembly::ExprType::Exnref;
1229*0b57cec5SDimitry Andric     break;
1230*0b57cec5SDimitry Andric   default:
1231*0b57cec5SDimitry Andric     llvm_unreachable("unexpected return type");
1232*0b57cec5SDimitry Andric   }
1233*0b57cec5SDimitry Andric 
1234*0b57cec5SDimitry Andric   for (MachineBasicBlock &MBB : reverse(MF)) {
1235*0b57cec5SDimitry Andric     for (MachineInstr &MI : reverse(MBB)) {
1236*0b57cec5SDimitry Andric       if (MI.isPosition() || MI.isDebugInstr())
1237*0b57cec5SDimitry Andric         continue;
1238*0b57cec5SDimitry Andric       if (MI.getOpcode() == WebAssembly::END_BLOCK) {
1239*0b57cec5SDimitry Andric         EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
1240*0b57cec5SDimitry Andric         continue;
1241*0b57cec5SDimitry Andric       }
1242*0b57cec5SDimitry Andric       if (MI.getOpcode() == WebAssembly::END_LOOP) {
1243*0b57cec5SDimitry Andric         EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
1244*0b57cec5SDimitry Andric         continue;
1245*0b57cec5SDimitry Andric       }
1246*0b57cec5SDimitry Andric       // Something other than an `end`. We're done.
1247*0b57cec5SDimitry Andric       return;
1248*0b57cec5SDimitry Andric     }
1249*0b57cec5SDimitry Andric   }
1250*0b57cec5SDimitry Andric }
1251*0b57cec5SDimitry Andric 
1252*0b57cec5SDimitry Andric // WebAssembly functions end with an end instruction, as if the function body
1253*0b57cec5SDimitry Andric // were a block.
1254*0b57cec5SDimitry Andric static void appendEndToFunction(MachineFunction &MF,
1255*0b57cec5SDimitry Andric                                 const WebAssemblyInstrInfo &TII) {
1256*0b57cec5SDimitry Andric   BuildMI(MF.back(), MF.back().end(),
1257*0b57cec5SDimitry Andric           MF.back().findPrevDebugLoc(MF.back().end()),
1258*0b57cec5SDimitry Andric           TII.get(WebAssembly::END_FUNCTION));
1259*0b57cec5SDimitry Andric }
1260*0b57cec5SDimitry Andric 
1261*0b57cec5SDimitry Andric /// Insert LOOP/TRY/BLOCK markers at appropriate places.
1262*0b57cec5SDimitry Andric void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) {
1263*0b57cec5SDimitry Andric   // We allocate one more than the number of blocks in the function to
1264*0b57cec5SDimitry Andric   // accommodate for the possible fake block we may insert at the end.
1265*0b57cec5SDimitry Andric   ScopeTops.resize(MF.getNumBlockIDs() + 1);
1266*0b57cec5SDimitry Andric   // Place the LOOP for MBB if MBB is the header of a loop.
1267*0b57cec5SDimitry Andric   for (auto &MBB : MF)
1268*0b57cec5SDimitry Andric     placeLoopMarker(MBB);
1269*0b57cec5SDimitry Andric 
1270*0b57cec5SDimitry Andric   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
1271*0b57cec5SDimitry Andric   for (auto &MBB : MF) {
1272*0b57cec5SDimitry Andric     if (MBB.isEHPad()) {
1273*0b57cec5SDimitry Andric       // Place the TRY for MBB if MBB is the EH pad of an exception.
1274*0b57cec5SDimitry Andric       if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1275*0b57cec5SDimitry Andric           MF.getFunction().hasPersonalityFn())
1276*0b57cec5SDimitry Andric         placeTryMarker(MBB);
1277*0b57cec5SDimitry Andric     } else {
1278*0b57cec5SDimitry Andric       // Place the BLOCK for MBB if MBB is branched to from above.
1279*0b57cec5SDimitry Andric       placeBlockMarker(MBB);
1280*0b57cec5SDimitry Andric     }
1281*0b57cec5SDimitry Andric   }
1282*0b57cec5SDimitry Andric   // Fix mismatches in unwind destinations induced by linearizing the code.
1283*0b57cec5SDimitry Andric   fixUnwindMismatches(MF);
1284*0b57cec5SDimitry Andric }
1285*0b57cec5SDimitry Andric 
1286*0b57cec5SDimitry Andric void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) {
1287*0b57cec5SDimitry Andric   // Now rewrite references to basic blocks to be depth immediates.
1288*0b57cec5SDimitry Andric   SmallVector<const MachineBasicBlock *, 8> Stack;
1289*0b57cec5SDimitry Andric   for (auto &MBB : reverse(MF)) {
1290*0b57cec5SDimitry Andric     for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) {
1291*0b57cec5SDimitry Andric       MachineInstr &MI = *I;
1292*0b57cec5SDimitry Andric       switch (MI.getOpcode()) {
1293*0b57cec5SDimitry Andric       case WebAssembly::BLOCK:
1294*0b57cec5SDimitry Andric       case WebAssembly::TRY:
1295*0b57cec5SDimitry Andric         assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <=
1296*0b57cec5SDimitry Andric                    MBB.getNumber() &&
1297*0b57cec5SDimitry Andric                "Block/try marker should be balanced");
1298*0b57cec5SDimitry Andric         Stack.pop_back();
1299*0b57cec5SDimitry Andric         break;
1300*0b57cec5SDimitry Andric 
1301*0b57cec5SDimitry Andric       case WebAssembly::LOOP:
1302*0b57cec5SDimitry Andric         assert(Stack.back() == &MBB && "Loop top should be balanced");
1303*0b57cec5SDimitry Andric         Stack.pop_back();
1304*0b57cec5SDimitry Andric         break;
1305*0b57cec5SDimitry Andric 
1306*0b57cec5SDimitry Andric       case WebAssembly::END_BLOCK:
1307*0b57cec5SDimitry Andric       case WebAssembly::END_TRY:
1308*0b57cec5SDimitry Andric         Stack.push_back(&MBB);
1309*0b57cec5SDimitry Andric         break;
1310*0b57cec5SDimitry Andric 
1311*0b57cec5SDimitry Andric       case WebAssembly::END_LOOP:
1312*0b57cec5SDimitry Andric         Stack.push_back(EndToBegin[&MI]->getParent());
1313*0b57cec5SDimitry Andric         break;
1314*0b57cec5SDimitry Andric 
1315*0b57cec5SDimitry Andric       default:
1316*0b57cec5SDimitry Andric         if (MI.isTerminator()) {
1317*0b57cec5SDimitry Andric           // Rewrite MBB operands to be depth immediates.
1318*0b57cec5SDimitry Andric           SmallVector<MachineOperand, 4> Ops(MI.operands());
1319*0b57cec5SDimitry Andric           while (MI.getNumOperands() > 0)
1320*0b57cec5SDimitry Andric             MI.RemoveOperand(MI.getNumOperands() - 1);
1321*0b57cec5SDimitry Andric           for (auto MO : Ops) {
1322*0b57cec5SDimitry Andric             if (MO.isMBB())
1323*0b57cec5SDimitry Andric               MO = MachineOperand::CreateImm(getDepth(Stack, MO.getMBB()));
1324*0b57cec5SDimitry Andric             MI.addOperand(MF, MO);
1325*0b57cec5SDimitry Andric           }
1326*0b57cec5SDimitry Andric         }
1327*0b57cec5SDimitry Andric         break;
1328*0b57cec5SDimitry Andric       }
1329*0b57cec5SDimitry Andric     }
1330*0b57cec5SDimitry Andric   }
1331*0b57cec5SDimitry Andric   assert(Stack.empty() && "Control flow should be balanced");
1332*0b57cec5SDimitry Andric }
1333*0b57cec5SDimitry Andric 
1334*0b57cec5SDimitry Andric void WebAssemblyCFGStackify::releaseMemory() {
1335*0b57cec5SDimitry Andric   ScopeTops.clear();
1336*0b57cec5SDimitry Andric   BeginToEnd.clear();
1337*0b57cec5SDimitry Andric   EndToBegin.clear();
1338*0b57cec5SDimitry Andric   TryToEHPad.clear();
1339*0b57cec5SDimitry Andric   EHPadToTry.clear();
1340*0b57cec5SDimitry Andric   AppendixBB = nullptr;
1341*0b57cec5SDimitry Andric }
1342*0b57cec5SDimitry Andric 
1343*0b57cec5SDimitry Andric bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
1344*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n"
1345*0b57cec5SDimitry Andric                        "********** Function: "
1346*0b57cec5SDimitry Andric                     << MF.getName() << '\n');
1347*0b57cec5SDimitry Andric   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
1348*0b57cec5SDimitry Andric 
1349*0b57cec5SDimitry Andric   releaseMemory();
1350*0b57cec5SDimitry Andric 
1351*0b57cec5SDimitry Andric   // Liveness is not tracked for VALUE_STACK physreg.
1352*0b57cec5SDimitry Andric   MF.getRegInfo().invalidateLiveness();
1353*0b57cec5SDimitry Andric 
1354*0b57cec5SDimitry Andric   // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes.
1355*0b57cec5SDimitry Andric   placeMarkers(MF);
1356*0b57cec5SDimitry Andric 
1357*0b57cec5SDimitry Andric   // Remove unnecessary instructions possibly introduced by try/end_trys.
1358*0b57cec5SDimitry Andric   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1359*0b57cec5SDimitry Andric       MF.getFunction().hasPersonalityFn())
1360*0b57cec5SDimitry Andric     removeUnnecessaryInstrs(MF);
1361*0b57cec5SDimitry Andric 
1362*0b57cec5SDimitry Andric   // Convert MBB operands in terminators to relative depth immediates.
1363*0b57cec5SDimitry Andric   rewriteDepthImmediates(MF);
1364*0b57cec5SDimitry Andric 
1365*0b57cec5SDimitry Andric   // Fix up block/loop/try signatures at the end of the function to conform to
1366*0b57cec5SDimitry Andric   // WebAssembly's rules.
1367*0b57cec5SDimitry Andric   fixEndsAtEndOfFunction(MF);
1368*0b57cec5SDimitry Andric 
1369*0b57cec5SDimitry Andric   // Add an end instruction at the end of the function body.
1370*0b57cec5SDimitry Andric   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1371*0b57cec5SDimitry Andric   if (!MF.getSubtarget<WebAssemblySubtarget>()
1372*0b57cec5SDimitry Andric            .getTargetTriple()
1373*0b57cec5SDimitry Andric            .isOSBinFormatELF())
1374*0b57cec5SDimitry Andric     appendEndToFunction(MF, TII);
1375*0b57cec5SDimitry Andric 
1376*0b57cec5SDimitry Andric   MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified();
1377*0b57cec5SDimitry Andric   return true;
1378*0b57cec5SDimitry Andric }
1379