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 "MCTargetDesc/WebAssemblyMCTargetDesc.h" 15 #include "WebAssembly.h" 16 #include "WebAssemblySubtarget.h" 17 #include "WebAssemblyUtilities.h" 18 #include "llvm/ADT/SmallSet.h" 19 #include "llvm/CodeGen/MachineInstrBuilder.h" 20 #include "llvm/CodeGen/WasmEHFuncInfo.h" 21 #include "llvm/MC/MCAsmInfo.h" 22 using namespace llvm; 23 24 #define DEBUG_TYPE "wasm-late-eh-prepare" 25 26 namespace { 27 class WebAssemblyLateEHPrepare final : public MachineFunctionPass { 28 StringRef getPassName() const override { 29 return "WebAssembly Late Prepare Exception"; 30 } 31 32 bool runOnMachineFunction(MachineFunction &MF) override; 33 bool removeUnnecessaryUnreachables(MachineFunction &MF); 34 bool replaceFuncletReturns(MachineFunction &MF); 35 bool addCatches(MachineFunction &MF); 36 bool addExceptionExtraction(MachineFunction &MF); 37 bool restoreStackPointer(MachineFunction &MF); 38 39 public: 40 static char ID; // Pass identification, replacement for typeid 41 WebAssemblyLateEHPrepare() : MachineFunctionPass(ID) {} 42 }; 43 } // end anonymous namespace 44 45 char WebAssemblyLateEHPrepare::ID = 0; 46 INITIALIZE_PASS(WebAssemblyLateEHPrepare, DEBUG_TYPE, 47 "WebAssembly Late Exception Preparation", false, false) 48 49 FunctionPass *llvm::createWebAssemblyLateEHPrepare() { 50 return new WebAssemblyLateEHPrepare(); 51 } 52 53 // Returns the nearest EH pad that dominates this instruction. This does not use 54 // dominator analysis; it just does BFS on its predecessors until arriving at an 55 // EH pad. This assumes valid EH scopes so the first EH pad it arrives in all 56 // possible search paths should be the same. 57 // Returns nullptr in case it does not find any EH pad in the search, or finds 58 // multiple different EH pads. 59 static MachineBasicBlock *getMatchingEHPad(MachineInstr *MI) { 60 MachineFunction *MF = MI->getParent()->getParent(); 61 SmallVector<MachineBasicBlock *, 2> WL; 62 SmallPtrSet<MachineBasicBlock *, 2> Visited; 63 WL.push_back(MI->getParent()); 64 MachineBasicBlock *EHPad = nullptr; 65 while (!WL.empty()) { 66 MachineBasicBlock *MBB = WL.pop_back_val(); 67 if (Visited.count(MBB)) 68 continue; 69 Visited.insert(MBB); 70 if (MBB->isEHPad()) { 71 if (EHPad && EHPad != MBB) 72 return nullptr; 73 EHPad = MBB; 74 continue; 75 } 76 if (MBB == &MF->front()) 77 return nullptr; 78 WL.append(MBB->pred_begin(), MBB->pred_end()); 79 } 80 return EHPad; 81 } 82 83 // Erase the specified BBs if the BB does not have any remaining predecessors, 84 // and also all its dead children. 85 template <typename Container> 86 static void eraseDeadBBsAndChildren(const Container &MBBs) { 87 SmallVector<MachineBasicBlock *, 8> WL(MBBs.begin(), MBBs.end()); 88 while (!WL.empty()) { 89 MachineBasicBlock *MBB = WL.pop_back_val(); 90 if (!MBB->pred_empty()) 91 continue; 92 SmallVector<MachineBasicBlock *, 4> Succs(MBB->succ_begin(), 93 MBB->succ_end()); 94 WL.append(MBB->succ_begin(), MBB->succ_end()); 95 for (auto *Succ : Succs) 96 MBB->removeSuccessor(Succ); 97 MBB->eraseFromParent(); 98 } 99 } 100 101 bool WebAssemblyLateEHPrepare::runOnMachineFunction(MachineFunction &MF) { 102 LLVM_DEBUG(dbgs() << "********** Late EH Prepare **********\n" 103 "********** Function: " 104 << MF.getName() << '\n'); 105 106 if (MF.getTarget().getMCAsmInfo()->getExceptionHandlingType() != 107 ExceptionHandling::Wasm) 108 return false; 109 110 bool Changed = false; 111 Changed |= removeUnnecessaryUnreachables(MF); 112 if (!MF.getFunction().hasPersonalityFn()) 113 return Changed; 114 Changed |= replaceFuncletReturns(MF); 115 Changed |= addCatches(MF); 116 Changed |= addExceptionExtraction(MF); 117 Changed |= restoreStackPointer(MF); 118 return Changed; 119 } 120 121 bool WebAssemblyLateEHPrepare::removeUnnecessaryUnreachables( 122 MachineFunction &MF) { 123 bool Changed = false; 124 for (auto &MBB : MF) { 125 for (auto &MI : MBB) { 126 if (MI.getOpcode() != WebAssembly::THROW && 127 MI.getOpcode() != WebAssembly::RETHROW) 128 continue; 129 Changed = true; 130 131 // The instruction after the throw should be an unreachable or a branch to 132 // another BB that should eventually lead to an unreachable. Delete it 133 // because throw itself is a terminator, and also delete successors if 134 // any. 135 MBB.erase(std::next(MI.getIterator()), MBB.end()); 136 SmallVector<MachineBasicBlock *, 8> Succs(MBB.succ_begin(), 137 MBB.succ_end()); 138 for (auto *Succ : Succs) 139 MBB.removeSuccessor(Succ); 140 eraseDeadBBsAndChildren(Succs); 141 } 142 } 143 144 return Changed; 145 } 146 147 bool WebAssemblyLateEHPrepare::replaceFuncletReturns(MachineFunction &MF) { 148 bool Changed = false; 149 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 150 151 for (auto &MBB : MF) { 152 auto Pos = MBB.getFirstTerminator(); 153 if (Pos == MBB.end()) 154 continue; 155 MachineInstr *TI = &*Pos; 156 157 switch (TI->getOpcode()) { 158 case WebAssembly::CATCHRET: { 159 // Replace a catchret with a branch 160 MachineBasicBlock *TBB = TI->getOperand(0).getMBB(); 161 if (!MBB.isLayoutSuccessor(TBB)) 162 BuildMI(MBB, TI, TI->getDebugLoc(), TII.get(WebAssembly::BR)) 163 .addMBB(TBB); 164 TI->eraseFromParent(); 165 Changed = true; 166 break; 167 } 168 case WebAssembly::CLEANUPRET: { 169 // Replace a cleanupret with a rethrow 170 BuildMI(MBB, TI, TI->getDebugLoc(), TII.get(WebAssembly::RETHROW)); 171 TI->eraseFromParent(); 172 Changed = true; 173 break; 174 } 175 } 176 } 177 return Changed; 178 } 179 180 // Add catch instruction to beginning of catchpads and cleanuppads. 181 bool WebAssemblyLateEHPrepare::addCatches(MachineFunction &MF) { 182 bool Changed = false; 183 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 184 MachineRegisterInfo &MRI = MF.getRegInfo(); 185 for (auto &MBB : MF) { 186 if (MBB.isEHPad()) { 187 Changed = true; 188 auto InsertPos = MBB.begin(); 189 if (InsertPos->isEHLabel()) // EH pad starts with an EH label 190 ++InsertPos; 191 unsigned DstReg = 192 MRI.createVirtualRegister(&WebAssembly::EXCEPT_REFRegClass); 193 BuildMI(MBB, InsertPos, MBB.begin()->getDebugLoc(), 194 TII.get(WebAssembly::CATCH), DstReg); 195 } 196 } 197 return Changed; 198 } 199 200 // Wasm uses 'br_on_exn' instruction to check the tag of an exception. It takes 201 // except_ref type object returned by 'catch', and branches to the destination 202 // if it matches a given tag. We currently use __cpp_exception symbol to 203 // represent the tag for all C++ exceptions. 204 // 205 // block $l (result i32) 206 // ... 207 // ;; except_ref $e is on the stack at this point 208 // br_on_exn $l $e ;; branch to $l with $e's arguments 209 // ... 210 // end 211 // ;; Here we expect the extracted values are on top of the wasm value stack 212 // ... Handle exception using values ... 213 // 214 // br_on_exn takes an except_ref object and branches if it matches the given 215 // tag. There can be multiple br_on_exn instructions if we want to match for 216 // another tag, but for now we only test for __cpp_exception tag, and if it does 217 // not match, i.e., it is a foreign exception, we rethrow it. 218 // 219 // In the destination BB that's the target of br_on_exn, extracted exception 220 // values (in C++'s case a single i32, which represents an exception pointer) 221 // are placed on top of the wasm stack. Because we can't model wasm stack in 222 // LLVM instruction, we use 'extract_exception' pseudo instruction to retrieve 223 // it. The pseudo instruction will be deleted later. 224 bool WebAssemblyLateEHPrepare::addExceptionExtraction(MachineFunction &MF) { 225 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 226 auto *EHInfo = MF.getWasmEHFuncInfo(); 227 SmallVector<MachineInstr *, 16> ExtractInstrs; 228 SmallVector<MachineInstr *, 8> ToDelete; 229 for (auto &MBB : MF) { 230 for (auto &MI : MBB) { 231 if (MI.getOpcode() == WebAssembly::EXTRACT_EXCEPTION_I32) { 232 if (MI.getOperand(0).isDead()) 233 ToDelete.push_back(&MI); 234 else 235 ExtractInstrs.push_back(&MI); 236 } 237 } 238 } 239 bool Changed = !ToDelete.empty() || !ExtractInstrs.empty(); 240 for (auto *MI : ToDelete) 241 MI->eraseFromParent(); 242 if (ExtractInstrs.empty()) 243 return Changed; 244 245 // Find terminate pads. 246 SmallSet<MachineBasicBlock *, 8> TerminatePads; 247 for (auto &MBB : MF) { 248 for (auto &MI : MBB) { 249 if (MI.isCall()) { 250 const MachineOperand &CalleeOp = MI.getOperand(0); 251 if (CalleeOp.isGlobal() && CalleeOp.getGlobal()->getName() == 252 WebAssembly::ClangCallTerminateFn) 253 TerminatePads.insert(getMatchingEHPad(&MI)); 254 } 255 } 256 } 257 258 for (auto *Extract : ExtractInstrs) { 259 MachineBasicBlock *EHPad = getMatchingEHPad(Extract); 260 assert(EHPad && "No matching EH pad for extract_exception"); 261 auto CatchPos = EHPad->begin(); 262 if (CatchPos->isEHLabel()) // EH pad starts with an EH label 263 ++CatchPos; 264 MachineInstr *Catch = &*CatchPos; 265 266 if (Catch->getNextNode() != Extract) 267 EHPad->insert(Catch->getNextNode(), Extract->removeFromParent()); 268 269 // - Before: 270 // ehpad: 271 // %exnref:except_ref = catch 272 // %exn:i32 = extract_exception 273 // ... use exn ... 274 // 275 // - After: 276 // ehpad: 277 // %exnref:except_ref = catch 278 // br_on_exn %thenbb, $__cpp_exception, %exnref 279 // br %elsebb 280 // elsebb: 281 // rethrow 282 // thenbb: 283 // %exn:i32 = extract_exception 284 // ... use exn ... 285 unsigned ExnReg = Catch->getOperand(0).getReg(); 286 auto *ThenMBB = MF.CreateMachineBasicBlock(); 287 auto *ElseMBB = MF.CreateMachineBasicBlock(); 288 MF.insert(std::next(MachineFunction::iterator(EHPad)), ElseMBB); 289 MF.insert(std::next(MachineFunction::iterator(ElseMBB)), ThenMBB); 290 ThenMBB->splice(ThenMBB->end(), EHPad, Extract, EHPad->end()); 291 ThenMBB->transferSuccessors(EHPad); 292 EHPad->addSuccessor(ThenMBB); 293 EHPad->addSuccessor(ElseMBB); 294 295 DebugLoc DL = Extract->getDebugLoc(); 296 const char *CPPExnSymbol = MF.createExternalSymbolName("__cpp_exception"); 297 BuildMI(EHPad, DL, TII.get(WebAssembly::BR_ON_EXN)) 298 .addMBB(ThenMBB) 299 .addExternalSymbol(CPPExnSymbol, WebAssemblyII::MO_SYMBOL_EVENT) 300 .addReg(ExnReg); 301 BuildMI(EHPad, DL, TII.get(WebAssembly::BR)).addMBB(ElseMBB); 302 303 // When this is a terminate pad with __clang_call_terminate() call, we don't 304 // rethrow it anymore and call __clang_call_terminate() with a nullptr 305 // argument, which will call std::terminate(). 306 // 307 // - Before: 308 // ehpad: 309 // %exnref:except_ref = catch 310 // %exn:i32 = extract_exception 311 // call @__clang_call_terminate(%exn) 312 // unreachable 313 // 314 // - After: 315 // ehpad: 316 // %exnref:except_ref = catch 317 // br_on_exn %thenbb, $__cpp_exception, %exnref 318 // br %elsebb 319 // elsebb: 320 // call @__clang_call_terminate(0) 321 // unreachable 322 // thenbb: 323 // %exn:i32 = extract_exception 324 // call @__clang_call_terminate(%exn) 325 // unreachable 326 if (TerminatePads.count(EHPad)) { 327 Function *ClangCallTerminateFn = 328 MF.getFunction().getParent()->getFunction( 329 WebAssembly::ClangCallTerminateFn); 330 assert(ClangCallTerminateFn && 331 "There is no __clang_call_terminate() function"); 332 BuildMI(ElseMBB, DL, TII.get(WebAssembly::CALL_VOID)) 333 .addGlobalAddress(ClangCallTerminateFn) 334 .addImm(0); 335 BuildMI(ElseMBB, DL, TII.get(WebAssembly::UNREACHABLE)); 336 337 } else { 338 BuildMI(ElseMBB, DL, TII.get(WebAssembly::RETHROW)); 339 if (EHInfo->hasEHPadUnwindDest(EHPad)) 340 ElseMBB->addSuccessor(EHInfo->getEHPadUnwindDest(EHPad)); 341 } 342 } 343 344 return true; 345 } 346 347 // After the stack is unwound due to a thrown exception, the __stack_pointer 348 // global can point to an invalid address. This inserts instructions that 349 // restore __stack_pointer global. 350 bool WebAssemblyLateEHPrepare::restoreStackPointer(MachineFunction &MF) { 351 const auto *FrameLowering = static_cast<const WebAssemblyFrameLowering *>( 352 MF.getSubtarget().getFrameLowering()); 353 if (!FrameLowering->needsPrologForEH(MF)) 354 return false; 355 bool Changed = false; 356 357 for (auto &MBB : MF) { 358 if (!MBB.isEHPad()) 359 continue; 360 Changed = true; 361 362 // Insert __stack_pointer restoring instructions at the beginning of each EH 363 // pad, after the catch instruction. Here it is safe to assume that SP32 364 // holds the latest value of __stack_pointer, because the only exception for 365 // this case is when a function uses the red zone, but that only happens 366 // with leaf functions, and we don't restore __stack_pointer in leaf 367 // functions anyway. 368 auto InsertPos = MBB.begin(); 369 if (InsertPos->isEHLabel()) // EH pad starts with an EH label 370 ++InsertPos; 371 if (InsertPos->getOpcode() == WebAssembly::CATCH) 372 ++InsertPos; 373 FrameLowering->writeSPToGlobal(WebAssembly::SP32, MF, MBB, InsertPos, 374 MBB.begin()->getDebugLoc()); 375 } 376 return Changed; 377 } 378