LLVM 24.0.0git
WebAssemblyLateEHPrepare.cpp
Go to the documentation of this file.
1//=== WebAssemblyLateEHPrepare.cpp - WebAssembly Exception Preparation -===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// \brief Does various transformations for exception handling.
11///
12//===----------------------------------------------------------------------===//
13
14#include "WebAssembly.h"
18#include "llvm/ADT/MapVector.h"
24#include "llvm/IR/Analysis.h"
25#include "llvm/IR/Module.h"
26#include "llvm/Support/Debug.h"
27using namespace llvm;
28
29#define DEBUG_TYPE "wasm-late-eh-prepare"
30
31namespace {
32class WebAssemblyLateEHPrepareImpl {
33 bool removeUnreachableEHPads(MachineFunction &MF);
34 void recordCatchRetBBs(MachineFunction &MF);
35 bool hoistCatches(MachineFunction &MF);
36 bool addCatchAlls(MachineFunction &MF);
37 bool addCatchRefsAndThrowRefs(MachineFunction &MF);
38 bool replaceFuncletReturns(MachineFunction &MF);
39 bool removeUnnecessaryUnreachables(MachineFunction &MF);
40 bool restoreStackPointer(MachineFunction &MF);
41
42 MachineBasicBlock *getMatchingEHPad(MachineInstr *MI);
44
45public:
46 bool runOnMachineFunction(MachineFunction &MF);
47};
48
49class WebAssemblyLateEHPrepareLegacy final : public MachineFunctionPass {
50 StringRef getPassName() const override {
51 return "WebAssembly Late Prepare Exception";
52 }
53
54 bool runOnMachineFunction(MachineFunction &MF) override;
55
56public:
57 static char ID; // Pass identification, replacement for typeid
58 WebAssemblyLateEHPrepareLegacy() : MachineFunctionPass(ID) {}
59};
60} // end anonymous namespace
61
62char WebAssemblyLateEHPrepareLegacy::ID = 0;
63INITIALIZE_PASS(WebAssemblyLateEHPrepareLegacy, DEBUG_TYPE,
64 "WebAssembly Late Exception Preparation", false, false)
65
67 return new WebAssemblyLateEHPrepareLegacy();
68}
69
70// Returns the nearest EH pad that dominates this instruction. This does not use
71// dominator analysis; it just does BFS on its predecessors until arriving at an
72// EH pad. This assumes valid EH scopes so the first EH pad it arrives in all
73// possible search paths should be the same.
74// Returns nullptr in case it does not find any EH pad in the search, or finds
75// multiple different EH pads.
77WebAssemblyLateEHPrepareImpl::getMatchingEHPad(MachineInstr *MI) {
78 MachineFunction *MF = MI->getParent()->getParent();
80 SmallPtrSet<MachineBasicBlock *, 2> Visited;
81 WL.push_back(MI->getParent());
82 MachineBasicBlock *EHPad = nullptr;
83 while (!WL.empty()) {
84 MachineBasicBlock *MBB = WL.pop_back_val();
85 if (!Visited.insert(MBB).second)
86 continue;
87 if (MBB->isEHPad()) {
88 if (EHPad && EHPad != MBB)
89 return nullptr;
90 EHPad = MBB;
91 continue;
92 }
93 if (MBB == &MF->front())
94 return nullptr;
95 for (auto *Pred : MBB->predecessors())
96 if (!CatchRetBBs.count(Pred)) // We don't go into child scopes
97 WL.push_back(Pred);
98 }
99 return EHPad;
100}
101
102// Erase the specified BBs if the BB does not have any remaining predecessors,
103// and also all its dead children.
104template <typename Container>
105static void eraseDeadBBsAndChildren(const Container &MBBs) {
106 SmallVector<MachineBasicBlock *, 8> WL(MBBs.begin(), MBBs.end());
108 while (!WL.empty()) {
110 if (Deleted.count(MBB) || !MBB->pred_empty())
111 continue;
112 SmallVector<MachineBasicBlock *, 4> Succs(MBB->successors());
113 WL.append(MBB->succ_begin(), MBB->succ_end());
114 for (auto *Succ : Succs)
115 MBB->removeSuccessor(Succ);
116 // To prevent deleting the same BB multiple times, which can happen when
117 // 'MBBs' contain both a parent and a child
118 Deleted.insert(MBB);
119 MBB->eraseFromParent();
120 }
121}
122
123bool WebAssemblyLateEHPrepareImpl::runOnMachineFunction(MachineFunction &MF) {
124 LLVM_DEBUG(dbgs() << "********** Late EH Prepare **********\n"
125 "********** Function: "
126 << MF.getName() << '\n');
127
129 ExceptionHandling::Wasm)
130 return false;
131
132 bool Changed = false;
133 if (MF.getFunction().hasPersonalityFn()) {
134 Changed |= removeUnreachableEHPads(MF);
135 recordCatchRetBBs(MF);
136 Changed |= hoistCatches(MF);
137 Changed |= addCatchAlls(MF);
138 Changed |= replaceFuncletReturns(MF);
139 if (!WebAssembly::WasmUseLegacyEH)
140 Changed |= addCatchRefsAndThrowRefs(MF);
141 }
142 Changed |= removeUnnecessaryUnreachables(MF);
143 if (MF.getFunction().hasPersonalityFn())
144 Changed |= restoreStackPointer(MF);
145 return Changed;
146}
147
148// Remove unreachable EH pads and its children. If they remain, CFG
149// stackification can be tricky.
150bool WebAssemblyLateEHPrepareImpl::removeUnreachableEHPads(
151 MachineFunction &MF) {
152 SmallVector<MachineBasicBlock *, 4> ToDelete;
153 for (auto &MBB : MF)
154 if (MBB.isEHPad() && MBB.pred_empty())
155 ToDelete.push_back(&MBB);
156 eraseDeadBBsAndChildren(ToDelete);
157 return !ToDelete.empty();
158}
159
160// Record which BB ends with catchret instruction, because this will be replaced
161// with 'br's later. This set of catchret BBs is necessary in 'getMatchingEHPad'
162// function.
163void WebAssemblyLateEHPrepareImpl::recordCatchRetBBs(MachineFunction &MF) {
164 CatchRetBBs.clear();
165 for (auto &MBB : MF) {
166 auto Pos = MBB.getFirstTerminator();
167 if (Pos == MBB.end())
168 continue;
169 MachineInstr *TI = &*Pos;
170 if (TI->getOpcode() == WebAssembly::CATCHRET)
171 CatchRetBBs.insert(&MBB);
172 }
173}
174
175// Hoist catch instructions to the beginning of their matching EH pad BBs in
176// case,
177// (1) catch instruction is not the first instruction in EH pad.
178// ehpad:
179// some_other_instruction
180// ...
181// %exn = catch 0
182// (2) catch instruction is in a non-EH pad BB. For example,
183// ehpad:
184// br bb0
185// bb0:
186// %exn = catch 0
187bool WebAssemblyLateEHPrepareImpl::hoistCatches(MachineFunction &MF) {
188 bool Changed = false;
190 for (auto &MBB : MF)
191 for (auto &MI : MBB)
192 if (WebAssembly::isCatch(MI.getOpcode()))
193 Catches.push_back(&MI);
194
195 for (auto *Catch : Catches) {
196 MachineBasicBlock *EHPad = getMatchingEHPad(Catch);
197 assert(EHPad && "No matching EH pad for catch");
198 auto InsertPos = EHPad->begin();
199 // Skip EH_LABELs in the beginning of an EH pad if present. We don't use
200 // these labels at the moment, but other targets also seem to have an
201 // EH_LABEL instruction in the beginning of an EH pad.
202 while (InsertPos != EHPad->end() && InsertPos->isEHLabel())
203 InsertPos++;
204 if (InsertPos == Catch)
205 continue;
206 Changed = true;
207 EHPad->insert(InsertPos, Catch->removeFromParent());
208 }
209 return Changed;
210}
211
212// Add catch_all to beginning of cleanup pads.
213bool WebAssemblyLateEHPrepareImpl::addCatchAlls(MachineFunction &MF) {
214 bool Changed = false;
215 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
216
217 for (auto &MBB : MF) {
218 if (!MBB.isEHPad())
219 continue;
220 auto InsertPos = MBB.begin();
221 // Skip EH_LABELs in the beginning of an EH pad if present.
222 while (InsertPos != MBB.end() && InsertPos->isEHLabel())
223 InsertPos++;
224 // This runs after hoistCatches(), so we assume that if there is a catch,
225 // that should be the first non-EH-label instruction in an EH pad.
226 if (InsertPos == MBB.end() ||
227 !WebAssembly::isCatch(InsertPos->getOpcode())) {
228 Changed = true;
229 unsigned CatchAllOpcode = WebAssembly::WasmUseLegacyEH
230 ? WebAssembly::CATCH_ALL_LEGACY
231 : WebAssembly::CATCH_ALL;
232 BuildMI(MBB, InsertPos,
233 InsertPos == MBB.end() ? DebugLoc() : InsertPos->getDebugLoc(),
234 TII.get(CatchAllOpcode));
235 }
236 }
237 return Changed;
238}
239
240// Replace pseudo-instructions catchret and cleanupret with br and rethrow
241// respectively.
242bool WebAssemblyLateEHPrepareImpl::replaceFuncletReturns(MachineFunction &MF) {
243 bool Changed = false;
244 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
245
246 for (auto &MBB : MF) {
247 auto Pos = MBB.getFirstTerminator();
248 if (Pos == MBB.end())
249 continue;
250 MachineInstr *TI = &*Pos;
251
252 switch (TI->getOpcode()) {
253 case WebAssembly::CATCHRET: {
254 // Replace a catchret with a branch
255 MachineBasicBlock *TBB = TI->getOperand(0).getMBB();
257 BuildMI(MBB, TI, TI->getDebugLoc(), TII.get(WebAssembly::BR))
258 .addMBB(TBB);
259 TI->eraseFromParent();
260 Changed = true;
261 break;
262 }
263 case WebAssembly::RETHROW:
264 // These RETHROWs here were lowered from llvm.wasm.rethrow() intrinsics,
265 // generated in Clang for when an exception is not caught by the given
266 // type (e.g. catch (int)).
267 //
268 // RETHROW's BB argument is the EH pad where the exception to rethrow has
269 // been caught. (Until this point, RETHROW has just a '0' as a placeholder
270 // argument.) For these llvm.wasm.rethrow()s, we can safely assume the
271 // exception comes from the nearest dominating EH pad, because catch.start
272 // EH pad is structured like this:
273 //
274 // catch.start:
275 // catchpad ...
276 // %matches = compare ehselector with typeid
277 // br i1 %matches, label %catch, label %rethrow
278 //
279 // rethrow:
280 // ;; rethrows the exception caught in 'catch.start'
281 // call @llvm.wasm.rethrow()
282 TI->removeOperand(0);
283 TI->addOperand(MachineOperand::CreateMBB(getMatchingEHPad(TI)));
284 Changed = true;
285 break;
286 case WebAssembly::CLEANUPRET: {
287 // CLEANUPRETs have the EH pad BB the exception to rethrow has been caught
288 // as an argument. Use it and change the instruction opcode to 'RETHROW'
289 // to make rethrowing instructions consistent.
290 //
291 // This is because we cannot safely assume that it is always the nearest
292 // dominating EH pad, in case there are code transformations such as
293 // inlining.
294 BuildMI(MBB, TI, TI->getDebugLoc(), TII.get(WebAssembly::RETHROW))
295 .addMBB(TI->getOperand(0).getMBB());
296 TI->eraseFromParent();
297 Changed = true;
298 break;
299 }
300 }
301 }
302 return Changed;
303}
304
305// Add CATCH_REF and CATCH_ALL_REF pseudo instructions to EH pads, and convert
306// RETHROWs to THROW_REFs.
307bool WebAssemblyLateEHPrepareImpl::addCatchRefsAndThrowRefs(
308 MachineFunction &MF) {
309 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
310 auto &MRI = MF.getRegInfo();
311 MapVector<MachineBasicBlock *, SmallVector<MachineInstr *, 2>>
312 EHPadToRethrows;
313
314 // Create a map of <EH pad, a vector of RETHROWs rethrowing its exception>
315 for (auto &MBB : MF)
316 for (auto &MI : MBB)
317 if (MI.getOpcode() == WebAssembly::RETHROW)
318 EHPadToRethrows[MI.getOperand(0).getMBB()].push_back(&MI);
319 if (EHPadToRethrows.empty())
320 return false;
321
322 // Convert CATCH into CATCH_REF and CATCH_ALL into CATCH_ALL_REF, when the
323 // caught exception is rethrown. And convert RETHROWs to THROW_REFs.
324 for (auto &[EHPad, Rethrows] : EHPadToRethrows) {
325 auto *Catch = WebAssembly::findCatch(EHPad);
326 assert(Catch && "CATCH not found in EHPad");
327 auto InsertPos = std::next(Catch->getIterator());
328 auto ExnReg = MRI.createVirtualRegister(&WebAssembly::EXNREFRegClass);
329 if (Catch->getOpcode() == WebAssembly::CATCH) {
330 MachineInstrBuilder MIB = BuildMI(*EHPad, InsertPos, Catch->getDebugLoc(),
331 TII.get(WebAssembly::CATCH_REF));
332 // Copy defs (= extracted values) from the old CATCH to the new CATCH_REF
333 for (const auto &Def : Catch->defs())
334 MIB.addDef(Def.getReg());
335 MIB.addDef(ExnReg); // Attach the exnref def after extracted values
336 // Copy the tag symbol (The only use operand a CATCH can have is the tag
337 // symbol)
338 for (const auto &Use : Catch->uses()) {
339 MIB.addExternalSymbol(Use.getSymbolName());
340 break;
341 }
342 } else if (Catch->getOpcode() == WebAssembly::CATCH_ALL) {
343 BuildMI(*EHPad, InsertPos, Catch->getDebugLoc(),
344 TII.get(WebAssembly::CATCH_ALL_REF))
345 .addDef(ExnReg);
346 } else {
347 assert(false);
348 }
349 Catch->eraseFromParent();
350
351 for (auto *Rethrow : Rethrows) {
352 auto InsertPos = std::next(Rethrow->getIterator());
353 BuildMI(*Rethrow->getParent(), InsertPos, Rethrow->getDebugLoc(),
354 TII.get(WebAssembly::THROW_REF))
355 .addReg(ExnReg);
356 Rethrow->eraseFromParent();
357 }
358 }
359
360 return true;
361}
362
363// Remove unnecessary unreachables after a throw/rethrow/throw_ref.
364bool WebAssemblyLateEHPrepareImpl::removeUnnecessaryUnreachables(
365 MachineFunction &MF) {
366 bool Changed = false;
367 for (auto &MBB : MF) {
368 for (auto &MI : MBB) {
369 if (MI.getOpcode() != WebAssembly::THROW &&
370 MI.getOpcode() != WebAssembly::RETHROW &&
371 MI.getOpcode() != WebAssembly::THROW_REF)
372 continue;
373 Changed = true;
374
375 // The instruction after the throw should be an unreachable or a branch to
376 // another BB that should eventually lead to an unreachable. Delete it
377 // because throw itself is a terminator, and also delete successors if
378 // any.
379 MBB.erase(std::next(MI.getIterator()), MBB.end());
381 for (auto *Succ : Succs)
382 if (!Succ->isEHPad())
383 MBB.removeSuccessor(Succ);
385 }
386 }
387
388 return Changed;
389}
390
391// After the stack is unwound due to a thrown exception, the __stack_pointer
392// global/__wasm_get_stack_pointer() can point to an invalid address. This
393// inserts instructions that restore the stack pointer state.
394bool WebAssemblyLateEHPrepareImpl::restoreStackPointer(MachineFunction &MF) {
395 const auto *FrameLowering = static_cast<const WebAssemblyFrameLowering *>(
396 MF.getSubtarget().getFrameLowering());
397 if (!FrameLowering->needsPrologForEH(MF))
398 return false;
399 bool Changed = false;
400
401 for (auto &MBB : MF) {
402 if (!MBB.isEHPad())
403 continue;
404 Changed = true;
405
406 // Insert stack pointer restoring instructions at the beginning of each EH
407 // pad, after the catch instruction. Here it is safe to assume that SP32
408 // holds the latest value of the stack pointer, because the only exception
409 // for this case is when a function uses the red zone, but that only happens
410 // with leaf functions, and we don't restore the stack pointer in leaf
411 // functions anyway.
412 auto InsertPos = MBB.begin();
413 // Skip EH_LABELs in the beginning of an EH pad if present.
414 while (InsertPos != MBB.end() && InsertPos->isEHLabel())
415 InsertPos++;
416 assert(InsertPos != MBB.end() &&
417 WebAssembly::isCatch(InsertPos->getOpcode()) &&
418 "catch/catch_all should be present in every EH pad at this point");
419 ++InsertPos; // Skip the catch instruction
420 FrameLowering->writeBackSP(FrameLowering->getSPReg(MF), MF, MBB, InsertPos,
421 MBB.begin()->getDebugLoc());
422 }
423 return Changed;
424}
425
426bool WebAssemblyLateEHPrepareLegacy::runOnMachineFunction(MachineFunction &MF) {
427 WebAssemblyLateEHPrepareImpl Impl;
428 return Impl.runOnMachineFunction(MF);
429}
430
431PreservedAnalyses
434 WebAssemblyLateEHPrepareImpl Impl;
435 return Impl.runOnMachineFunction(MF)
438}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This file implements a map that provides insertion order iteration.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file defines the SmallPtrSet class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static void eraseDeadBBsAndChildren(const Container &BBs)
This file declares the WebAssembly-specific subclass of TargetSubtarget.
This file declares the WebAssembly-specific subclass of TargetMachine.
This file contains the declaration of the WebAssembly-specific utility functions.
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:890
Module * getParent()
Get the module that this global value is contained inside of...
bool isEHPad() const
Returns true if the block is a landing pad.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
LLVM_ABI bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & front() const
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned TargetFlags=0) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
LLVM_ABI void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
MachineBasicBlock * getMBB() const
static MachineOperand CreateMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0)
bool empty() const
Definition MapVector.h:79
ExceptionHandling getExceptionModel() const
Returns the exception model recorded by the "exception-model" module flag, or ExceptionHandling::Defa...
Definition Module.cpp:719
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Changed
Pass manager infrastructure for declaring and invalidating analyses.
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
FunctionPass * createWebAssemblyLateEHPrepareLegacyPass()