xref: /llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyFixBrTableDefaults.cpp (revision 8ebe499e07760b0d18b5721b298efc9e4a241916)
17f50c15bSThomas Lively //=- WebAssemblyFixBrTableDefaults.cpp - Fix br_table default branch targets -//
27f50c15bSThomas Lively //
37f50c15bSThomas Lively // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47f50c15bSThomas Lively // See https://llvm.org/LICENSE.txt for license information.
57f50c15bSThomas Lively // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67f50c15bSThomas Lively //
77f50c15bSThomas Lively //===----------------------------------------------------------------------===//
87f50c15bSThomas Lively ///
97f50c15bSThomas Lively /// \file This file implements a pass that eliminates redundant range checks
107f50c15bSThomas Lively /// guarding br_table instructions. Since jump tables on most targets cannot
117f50c15bSThomas Lively /// handle out of range indices, LLVM emits these checks before most jump
127f50c15bSThomas Lively /// tables. But br_table takes a default branch target as an argument, so it
137f50c15bSThomas Lively /// does not need the range checks.
147f50c15bSThomas Lively ///
157f50c15bSThomas Lively //===----------------------------------------------------------------------===//
167f50c15bSThomas Lively 
177f50c15bSThomas Lively #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
187f50c15bSThomas Lively #include "WebAssembly.h"
19984dc4b9SReid Kleckner #include "WebAssemblySubtarget.h"
207f50c15bSThomas Lively #include "llvm/CodeGen/MachineFunction.h"
217f50c15bSThomas Lively #include "llvm/CodeGen/MachineFunctionPass.h"
227f50c15bSThomas Lively #include "llvm/CodeGen/MachineRegisterInfo.h"
237f50c15bSThomas Lively #include "llvm/Pass.h"
247f50c15bSThomas Lively 
257f50c15bSThomas Lively using namespace llvm;
267f50c15bSThomas Lively 
277f50c15bSThomas Lively #define DEBUG_TYPE "wasm-fix-br-table-defaults"
287f50c15bSThomas Lively 
297f50c15bSThomas Lively namespace {
307f50c15bSThomas Lively 
317f50c15bSThomas Lively class WebAssemblyFixBrTableDefaults final : public MachineFunctionPass {
327f50c15bSThomas Lively   StringRef getPassName() const override {
337f50c15bSThomas Lively     return "WebAssembly Fix br_table Defaults";
347f50c15bSThomas Lively   }
357f50c15bSThomas Lively 
367f50c15bSThomas Lively   bool runOnMachineFunction(MachineFunction &MF) override;
377f50c15bSThomas Lively 
387f50c15bSThomas Lively public:
397f50c15bSThomas Lively   static char ID; // Pass identification, replacement for typeid
407f50c15bSThomas Lively   WebAssemblyFixBrTableDefaults() : MachineFunctionPass(ID) {}
417f50c15bSThomas Lively };
427f50c15bSThomas Lively 
437f50c15bSThomas Lively char WebAssemblyFixBrTableDefaults::ID = 0;
447f50c15bSThomas Lively 
45*8ebe499eSJay Foad // Target independent selection dag assumes that it is ok to use PointerTy
46ce1eb7afSWouter van Oortmerssen // as the index for a "switch", whereas Wasm so far only has a 32-bit br_table.
47ce1eb7afSWouter van Oortmerssen // See e.g. SelectionDAGBuilder::visitJumpTableHeader
48ce1eb7afSWouter van Oortmerssen // We have a 64-bit br_table in the tablegen defs as a result, which does get
49ce1eb7afSWouter van Oortmerssen // selected, and thus we get incorrect truncates/extensions happening on
50ce1eb7afSWouter van Oortmerssen // wasm64. Here we fix that.
51ce1eb7afSWouter van Oortmerssen void fixBrTableIndex(MachineInstr &MI, MachineBasicBlock *MBB,
52ce1eb7afSWouter van Oortmerssen                      MachineFunction &MF) {
53ce1eb7afSWouter van Oortmerssen   // Only happens on wasm64.
54ce1eb7afSWouter van Oortmerssen   auto &WST = MF.getSubtarget<WebAssemblySubtarget>();
55ce1eb7afSWouter van Oortmerssen   if (!WST.hasAddr64())
56ce1eb7afSWouter van Oortmerssen     return;
57ce1eb7afSWouter van Oortmerssen 
58ce1eb7afSWouter van Oortmerssen   assert(MI.getDesc().getOpcode() == WebAssembly::BR_TABLE_I64 &&
59ce1eb7afSWouter van Oortmerssen          "64-bit br_table pseudo instruction expected");
60ce1eb7afSWouter van Oortmerssen 
61ce1eb7afSWouter van Oortmerssen   // Find extension op, if any. It sits in the previous BB before the branch.
62ce1eb7afSWouter van Oortmerssen   auto ExtMI = MF.getRegInfo().getVRegDef(MI.getOperand(0).getReg());
63ce1eb7afSWouter van Oortmerssen   if (ExtMI->getOpcode() == WebAssembly::I64_EXTEND_U_I32) {
64ce1eb7afSWouter van Oortmerssen     // Unnecessarily extending a 32-bit value to 64, remove it.
654a0c89a6SWouter van Oortmerssen     auto ExtDefReg = ExtMI->getOperand(0).getReg();
664a0c89a6SWouter van Oortmerssen     assert(MI.getOperand(0).getReg() == ExtDefReg);
67ce1eb7afSWouter van Oortmerssen     MI.getOperand(0).setReg(ExtMI->getOperand(1).getReg());
684a0c89a6SWouter van Oortmerssen     if (MF.getRegInfo().use_nodbg_empty(ExtDefReg)) {
694a0c89a6SWouter van Oortmerssen       // No more users of extend, delete it.
70ce1eb7afSWouter van Oortmerssen       ExtMI->eraseFromParent();
714a0c89a6SWouter van Oortmerssen     }
72ce1eb7afSWouter van Oortmerssen   } else {
73ce1eb7afSWouter van Oortmerssen     // Incoming 64-bit value that needs to be truncated.
74ce1eb7afSWouter van Oortmerssen     Register Reg32 =
75ce1eb7afSWouter van Oortmerssen         MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass);
76ce1eb7afSWouter van Oortmerssen     BuildMI(*MBB, MI.getIterator(), MI.getDebugLoc(),
77ce1eb7afSWouter van Oortmerssen             WST.getInstrInfo()->get(WebAssembly::I32_WRAP_I64), Reg32)
78ce1eb7afSWouter van Oortmerssen         .addReg(MI.getOperand(0).getReg());
79ce1eb7afSWouter van Oortmerssen     MI.getOperand(0).setReg(Reg32);
80ce1eb7afSWouter van Oortmerssen   }
81ce1eb7afSWouter van Oortmerssen 
82ce1eb7afSWouter van Oortmerssen   // We now have a 32-bit operand in all cases, so change the instruction
83ce1eb7afSWouter van Oortmerssen   // accordingly.
84ce1eb7afSWouter van Oortmerssen   MI.setDesc(WST.getInstrInfo()->get(WebAssembly::BR_TABLE_I32));
85ce1eb7afSWouter van Oortmerssen }
86ce1eb7afSWouter van Oortmerssen 
878df30d98SThomas Lively // `MI` is a br_table instruction with a dummy default target argument. This
887f50c15bSThomas Lively // function finds and adds the default target argument and removes any redundant
898df30d98SThomas Lively // range check preceding the br_table. Returns the MBB that the br_table is
908df30d98SThomas Lively // moved into so it can be removed from further consideration, or nullptr if the
918df30d98SThomas Lively // br_table cannot be optimized.
92ce1eb7afSWouter van Oortmerssen MachineBasicBlock *fixBrTableDefault(MachineInstr &MI, MachineBasicBlock *MBB,
937f50c15bSThomas Lively                                      MachineFunction &MF) {
947f50c15bSThomas Lively   // Get the header block, which contains the redundant range check.
957f50c15bSThomas Lively   assert(MBB->pred_size() == 1 && "Expected a single guard predecessor");
967f50c15bSThomas Lively   auto *HeaderMBB = *MBB->pred_begin();
977f50c15bSThomas Lively 
987f50c15bSThomas Lively   // Find the conditional jump to the default target. If it doesn't exist, the
998df30d98SThomas Lively   // default target is unreachable anyway, so we can keep the existing dummy
1008df30d98SThomas Lively   // target.
10149754dcfSThomas Lively   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
10249754dcfSThomas Lively   SmallVector<MachineOperand, 2> Cond;
10349754dcfSThomas Lively   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1048df30d98SThomas Lively   bool Analyzed = !TII.analyzeBranch(*HeaderMBB, TBB, FBB, Cond);
1058df30d98SThomas Lively   assert(Analyzed && "Could not analyze jump header branches");
1062247f721SAlexander Belyaev   (void)Analyzed;
10749754dcfSThomas Lively 
10849754dcfSThomas Lively   // Here are the possible outcomes. '_' is nullptr, `J` is the jump table block
10949754dcfSThomas Lively   // aka MBB, 'D' is the default block.
11049754dcfSThomas Lively   //
11149754dcfSThomas Lively   // TBB | FBB | Meaning
11249754dcfSThomas Lively   //  _  |  _  | No default block, header falls through to jump table
11349754dcfSThomas Lively   //  J  |  _  | No default block, header jumps to the jump table
11449754dcfSThomas Lively   //  D  |  _  | Header jumps to the default and falls through to the jump table
11549754dcfSThomas Lively   //  D  |  J  | Header jumps to the default and also to the jump table
11649754dcfSThomas Lively   if (TBB && TBB != MBB) {
11749754dcfSThomas Lively     assert((FBB == nullptr || FBB == MBB) &&
11849754dcfSThomas Lively            "Expected jump or fallthrough to br_table block");
1198df30d98SThomas Lively     assert(Cond.size() == 2 && Cond[1].isReg() && "Unexpected condition info");
1208df30d98SThomas Lively 
1218df30d98SThomas Lively     // If the range check checks an i64 value, we cannot optimize it out because
1228df30d98SThomas Lively     // the i64 index is truncated to an i32, making values over 2^32
12365330f39SThomas Lively     // indistinguishable from small numbers. There are also other strange edge
12465330f39SThomas Lively     // cases that can arise in practice that we don't want to reason about, so
12565330f39SThomas Lively     // conservatively only perform the optimization if the range check is the
12665330f39SThomas Lively     // normal case of an i32.gt_u.
1278df30d98SThomas Lively     MachineRegisterInfo &MRI = MF.getRegInfo();
1288df30d98SThomas Lively     auto *RangeCheck = MRI.getVRegDef(Cond[1].getReg());
1298df30d98SThomas Lively     assert(RangeCheck != nullptr);
13065330f39SThomas Lively     if (RangeCheck->getOpcode() != WebAssembly::GT_U_I32)
1318df30d98SThomas Lively       return nullptr;
1328df30d98SThomas Lively 
1338df30d98SThomas Lively     // Remove the dummy default target and install the real one.
13437b37838SShengchen Kan     MI.removeOperand(MI.getNumExplicitOperands() - 1);
13549754dcfSThomas Lively     MI.addOperand(MF, MachineOperand::CreateMBB(TBB));
1367f50c15bSThomas Lively   }
1377f50c15bSThomas Lively 
13849754dcfSThomas Lively   // Remove any branches from the header and splice in the jump table instead
13949754dcfSThomas Lively   TII.removeBranch(*HeaderMBB, nullptr);
1407f50c15bSThomas Lively   HeaderMBB->splice(HeaderMBB->end(), MBB, MBB->begin(), MBB->end());
1417f50c15bSThomas Lively 
1427f50c15bSThomas Lively   // Update CFG to skip the old jump table block. Remove shared successors
1437f50c15bSThomas Lively   // before transferring to avoid duplicated successors.
1447f50c15bSThomas Lively   HeaderMBB->removeSuccessor(MBB);
1457f50c15bSThomas Lively   for (auto &Succ : MBB->successors())
1467f50c15bSThomas Lively     if (HeaderMBB->isSuccessor(Succ))
1477f50c15bSThomas Lively       HeaderMBB->removeSuccessor(Succ);
1487f50c15bSThomas Lively   HeaderMBB->transferSuccessorsAndUpdatePHIs(MBB);
1497f50c15bSThomas Lively 
1507f50c15bSThomas Lively   // Remove the old jump table block from the function
1517f50c15bSThomas Lively   MF.erase(MBB);
1527f50c15bSThomas Lively 
1537f50c15bSThomas Lively   return HeaderMBB;
1547f50c15bSThomas Lively }
1557f50c15bSThomas Lively 
1567f50c15bSThomas Lively bool WebAssemblyFixBrTableDefaults::runOnMachineFunction(MachineFunction &MF) {
1577f50c15bSThomas Lively   LLVM_DEBUG(dbgs() << "********** Fixing br_table Default Targets **********\n"
1587f50c15bSThomas Lively                        "********** Function: "
1597f50c15bSThomas Lively                     << MF.getName() << '\n');
1607f50c15bSThomas Lively 
1617f50c15bSThomas Lively   bool Changed = false;
162dbca8aa1SDerek Schuff   SetVector<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 16>,
163dbca8aa1SDerek Schuff             DenseSet<MachineBasicBlock *>, 16>
164dbca8aa1SDerek Schuff       MBBSet;
1657f50c15bSThomas Lively   for (auto &MBB : MF)
1667f50c15bSThomas Lively     MBBSet.insert(&MBB);
1677f50c15bSThomas Lively 
1687f50c15bSThomas Lively   while (!MBBSet.empty()) {
1697f50c15bSThomas Lively     MachineBasicBlock *MBB = *MBBSet.begin();
170dbca8aa1SDerek Schuff     MBBSet.remove(MBB);
1717f50c15bSThomas Lively     for (auto &MI : *MBB) {
172984dc4b9SReid Kleckner       if (WebAssembly::isBrTable(MI.getOpcode())) {
173ce1eb7afSWouter van Oortmerssen         fixBrTableIndex(MI, MBB, MF);
174ce1eb7afSWouter van Oortmerssen         auto *Fixed = fixBrTableDefault(MI, MBB, MF);
1758df30d98SThomas Lively         if (Fixed != nullptr) {
176dbca8aa1SDerek Schuff           MBBSet.remove(Fixed);
1777f50c15bSThomas Lively           Changed = true;
1788df30d98SThomas Lively         }
1797f50c15bSThomas Lively         break;
1807f50c15bSThomas Lively       }
1817f50c15bSThomas Lively     }
1827f50c15bSThomas Lively   }
1837f50c15bSThomas Lively 
1847f50c15bSThomas Lively   if (Changed) {
1857f50c15bSThomas Lively     // We rewrote part of the function; recompute relevant things.
1867f50c15bSThomas Lively     MF.RenumberBlocks();
1877f50c15bSThomas Lively     return true;
1887f50c15bSThomas Lively   }
1897f50c15bSThomas Lively 
1907f50c15bSThomas Lively   return false;
1917f50c15bSThomas Lively }
1927f50c15bSThomas Lively 
1937f50c15bSThomas Lively } // end anonymous namespace
1947f50c15bSThomas Lively 
1957f50c15bSThomas Lively INITIALIZE_PASS(WebAssemblyFixBrTableDefaults, DEBUG_TYPE,
1967f50c15bSThomas Lively                 "Removes range checks and sets br_table default targets", false,
1972f671c42SMikael Holmen                 false)
1987f50c15bSThomas Lively 
1997f50c15bSThomas Lively FunctionPass *llvm::createWebAssemblyFixBrTableDefaults() {
2007f50c15bSThomas Lively   return new WebAssemblyFixBrTableDefaults();
2017f50c15bSThomas Lively }
202