15ffd83dbSDimitry Andric //=- WebAssemblyFixBrTableDefaults.cpp - Fix br_table default branch targets -//
25ffd83dbSDimitry Andric //
35ffd83dbSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
45ffd83dbSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
55ffd83dbSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65ffd83dbSDimitry Andric //
75ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
85ffd83dbSDimitry Andric ///
95ffd83dbSDimitry Andric /// \file This file implements a pass that eliminates redundant range checks
105ffd83dbSDimitry Andric /// guarding br_table instructions. Since jump tables on most targets cannot
115ffd83dbSDimitry Andric /// handle out of range indices, LLVM emits these checks before most jump
125ffd83dbSDimitry Andric /// tables. But br_table takes a default branch target as an argument, so it
135ffd83dbSDimitry Andric /// does not need the range checks.
145ffd83dbSDimitry Andric ///
155ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
165ffd83dbSDimitry Andric
175ffd83dbSDimitry Andric #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
185ffd83dbSDimitry Andric #include "WebAssembly.h"
195ffd83dbSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
205ffd83dbSDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
215ffd83dbSDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
225ffd83dbSDimitry Andric #include "llvm/Pass.h"
235ffd83dbSDimitry Andric
245ffd83dbSDimitry Andric using namespace llvm;
255ffd83dbSDimitry Andric
265ffd83dbSDimitry Andric #define DEBUG_TYPE "wasm-fix-br-table-defaults"
275ffd83dbSDimitry Andric
285ffd83dbSDimitry Andric namespace {
295ffd83dbSDimitry Andric
305ffd83dbSDimitry Andric class WebAssemblyFixBrTableDefaults final : public MachineFunctionPass {
getPassName() const315ffd83dbSDimitry Andric StringRef getPassName() const override {
325ffd83dbSDimitry Andric return "WebAssembly Fix br_table Defaults";
335ffd83dbSDimitry Andric }
345ffd83dbSDimitry Andric
355ffd83dbSDimitry Andric bool runOnMachineFunction(MachineFunction &MF) override;
365ffd83dbSDimitry Andric
375ffd83dbSDimitry Andric public:
385ffd83dbSDimitry Andric static char ID; // Pass identification, replacement for typeid
WebAssemblyFixBrTableDefaults()395ffd83dbSDimitry Andric WebAssemblyFixBrTableDefaults() : MachineFunctionPass(ID) {}
405ffd83dbSDimitry Andric };
415ffd83dbSDimitry Andric
425ffd83dbSDimitry Andric char WebAssemblyFixBrTableDefaults::ID = 0;
435ffd83dbSDimitry Andric
44*af732203SDimitry Andric // Target indepedent selection dag assumes that it is ok to use PointerTy
45*af732203SDimitry Andric // as the index for a "switch", whereas Wasm so far only has a 32-bit br_table.
46*af732203SDimitry Andric // See e.g. SelectionDAGBuilder::visitJumpTableHeader
47*af732203SDimitry Andric // We have a 64-bit br_table in the tablegen defs as a result, which does get
48*af732203SDimitry Andric // selected, and thus we get incorrect truncates/extensions happening on
49*af732203SDimitry Andric // wasm64. Here we fix that.
fixBrTableIndex(MachineInstr & MI,MachineBasicBlock * MBB,MachineFunction & MF)50*af732203SDimitry Andric void fixBrTableIndex(MachineInstr &MI, MachineBasicBlock *MBB,
51*af732203SDimitry Andric MachineFunction &MF) {
52*af732203SDimitry Andric // Only happens on wasm64.
53*af732203SDimitry Andric auto &WST = MF.getSubtarget<WebAssemblySubtarget>();
54*af732203SDimitry Andric if (!WST.hasAddr64())
55*af732203SDimitry Andric return;
56*af732203SDimitry Andric
57*af732203SDimitry Andric assert(MI.getDesc().getOpcode() == WebAssembly::BR_TABLE_I64 &&
58*af732203SDimitry Andric "64-bit br_table pseudo instruction expected");
59*af732203SDimitry Andric
60*af732203SDimitry Andric // Find extension op, if any. It sits in the previous BB before the branch.
61*af732203SDimitry Andric auto ExtMI = MF.getRegInfo().getVRegDef(MI.getOperand(0).getReg());
62*af732203SDimitry Andric if (ExtMI->getOpcode() == WebAssembly::I64_EXTEND_U_I32) {
63*af732203SDimitry Andric // Unnecessarily extending a 32-bit value to 64, remove it.
64*af732203SDimitry Andric assert(MI.getOperand(0).getReg() == ExtMI->getOperand(0).getReg());
65*af732203SDimitry Andric MI.getOperand(0).setReg(ExtMI->getOperand(1).getReg());
66*af732203SDimitry Andric ExtMI->eraseFromParent();
67*af732203SDimitry Andric } else {
68*af732203SDimitry Andric // Incoming 64-bit value that needs to be truncated.
69*af732203SDimitry Andric Register Reg32 =
70*af732203SDimitry Andric MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass);
71*af732203SDimitry Andric BuildMI(*MBB, MI.getIterator(), MI.getDebugLoc(),
72*af732203SDimitry Andric WST.getInstrInfo()->get(WebAssembly::I32_WRAP_I64), Reg32)
73*af732203SDimitry Andric .addReg(MI.getOperand(0).getReg());
74*af732203SDimitry Andric MI.getOperand(0).setReg(Reg32);
75*af732203SDimitry Andric }
76*af732203SDimitry Andric
77*af732203SDimitry Andric // We now have a 32-bit operand in all cases, so change the instruction
78*af732203SDimitry Andric // accordingly.
79*af732203SDimitry Andric MI.setDesc(WST.getInstrInfo()->get(WebAssembly::BR_TABLE_I32));
80*af732203SDimitry Andric }
81*af732203SDimitry Andric
825ffd83dbSDimitry Andric // `MI` is a br_table instruction with a dummy default target argument. This
835ffd83dbSDimitry Andric // function finds and adds the default target argument and removes any redundant
845ffd83dbSDimitry Andric // range check preceding the br_table. Returns the MBB that the br_table is
855ffd83dbSDimitry Andric // moved into so it can be removed from further consideration, or nullptr if the
865ffd83dbSDimitry Andric // br_table cannot be optimized.
fixBrTableDefault(MachineInstr & MI,MachineBasicBlock * MBB,MachineFunction & MF)87*af732203SDimitry Andric MachineBasicBlock *fixBrTableDefault(MachineInstr &MI, MachineBasicBlock *MBB,
885ffd83dbSDimitry Andric MachineFunction &MF) {
895ffd83dbSDimitry Andric // Get the header block, which contains the redundant range check.
905ffd83dbSDimitry Andric assert(MBB->pred_size() == 1 && "Expected a single guard predecessor");
915ffd83dbSDimitry Andric auto *HeaderMBB = *MBB->pred_begin();
925ffd83dbSDimitry Andric
935ffd83dbSDimitry Andric // Find the conditional jump to the default target. If it doesn't exist, the
945ffd83dbSDimitry Andric // default target is unreachable anyway, so we can keep the existing dummy
955ffd83dbSDimitry Andric // target.
965ffd83dbSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
975ffd83dbSDimitry Andric SmallVector<MachineOperand, 2> Cond;
985ffd83dbSDimitry Andric const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
995ffd83dbSDimitry Andric bool Analyzed = !TII.analyzeBranch(*HeaderMBB, TBB, FBB, Cond);
1005ffd83dbSDimitry Andric assert(Analyzed && "Could not analyze jump header branches");
1015ffd83dbSDimitry Andric (void)Analyzed;
1025ffd83dbSDimitry Andric
1035ffd83dbSDimitry Andric // Here are the possible outcomes. '_' is nullptr, `J` is the jump table block
1045ffd83dbSDimitry Andric // aka MBB, 'D' is the default block.
1055ffd83dbSDimitry Andric //
1065ffd83dbSDimitry Andric // TBB | FBB | Meaning
1075ffd83dbSDimitry Andric // _ | _ | No default block, header falls through to jump table
1085ffd83dbSDimitry Andric // J | _ | No default block, header jumps to the jump table
1095ffd83dbSDimitry Andric // D | _ | Header jumps to the default and falls through to the jump table
1105ffd83dbSDimitry Andric // D | J | Header jumps to the default and also to the jump table
1115ffd83dbSDimitry Andric if (TBB && TBB != MBB) {
1125ffd83dbSDimitry Andric assert((FBB == nullptr || FBB == MBB) &&
1135ffd83dbSDimitry Andric "Expected jump or fallthrough to br_table block");
1145ffd83dbSDimitry Andric assert(Cond.size() == 2 && Cond[1].isReg() && "Unexpected condition info");
1155ffd83dbSDimitry Andric
1165ffd83dbSDimitry Andric // If the range check checks an i64 value, we cannot optimize it out because
1175ffd83dbSDimitry Andric // the i64 index is truncated to an i32, making values over 2^32
1185ffd83dbSDimitry Andric // indistinguishable from small numbers. There are also other strange edge
1195ffd83dbSDimitry Andric // cases that can arise in practice that we don't want to reason about, so
1205ffd83dbSDimitry Andric // conservatively only perform the optimization if the range check is the
1215ffd83dbSDimitry Andric // normal case of an i32.gt_u.
1225ffd83dbSDimitry Andric MachineRegisterInfo &MRI = MF.getRegInfo();
1235ffd83dbSDimitry Andric auto *RangeCheck = MRI.getVRegDef(Cond[1].getReg());
1245ffd83dbSDimitry Andric assert(RangeCheck != nullptr);
1255ffd83dbSDimitry Andric if (RangeCheck->getOpcode() != WebAssembly::GT_U_I32)
1265ffd83dbSDimitry Andric return nullptr;
1275ffd83dbSDimitry Andric
1285ffd83dbSDimitry Andric // Remove the dummy default target and install the real one.
1295ffd83dbSDimitry Andric MI.RemoveOperand(MI.getNumExplicitOperands() - 1);
1305ffd83dbSDimitry Andric MI.addOperand(MF, MachineOperand::CreateMBB(TBB));
1315ffd83dbSDimitry Andric }
1325ffd83dbSDimitry Andric
1335ffd83dbSDimitry Andric // Remove any branches from the header and splice in the jump table instead
1345ffd83dbSDimitry Andric TII.removeBranch(*HeaderMBB, nullptr);
1355ffd83dbSDimitry Andric HeaderMBB->splice(HeaderMBB->end(), MBB, MBB->begin(), MBB->end());
1365ffd83dbSDimitry Andric
1375ffd83dbSDimitry Andric // Update CFG to skip the old jump table block. Remove shared successors
1385ffd83dbSDimitry Andric // before transferring to avoid duplicated successors.
1395ffd83dbSDimitry Andric HeaderMBB->removeSuccessor(MBB);
1405ffd83dbSDimitry Andric for (auto &Succ : MBB->successors())
1415ffd83dbSDimitry Andric if (HeaderMBB->isSuccessor(Succ))
1425ffd83dbSDimitry Andric HeaderMBB->removeSuccessor(Succ);
1435ffd83dbSDimitry Andric HeaderMBB->transferSuccessorsAndUpdatePHIs(MBB);
1445ffd83dbSDimitry Andric
1455ffd83dbSDimitry Andric // Remove the old jump table block from the function
1465ffd83dbSDimitry Andric MF.erase(MBB);
1475ffd83dbSDimitry Andric
1485ffd83dbSDimitry Andric return HeaderMBB;
1495ffd83dbSDimitry Andric }
1505ffd83dbSDimitry Andric
runOnMachineFunction(MachineFunction & MF)1515ffd83dbSDimitry Andric bool WebAssemblyFixBrTableDefaults::runOnMachineFunction(MachineFunction &MF) {
1525ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "********** Fixing br_table Default Targets **********\n"
1535ffd83dbSDimitry Andric "********** Function: "
1545ffd83dbSDimitry Andric << MF.getName() << '\n');
1555ffd83dbSDimitry Andric
1565ffd83dbSDimitry Andric bool Changed = false;
1575ffd83dbSDimitry Andric SmallPtrSet<MachineBasicBlock *, 16> MBBSet;
1585ffd83dbSDimitry Andric for (auto &MBB : MF)
1595ffd83dbSDimitry Andric MBBSet.insert(&MBB);
1605ffd83dbSDimitry Andric
1615ffd83dbSDimitry Andric while (!MBBSet.empty()) {
1625ffd83dbSDimitry Andric MachineBasicBlock *MBB = *MBBSet.begin();
1635ffd83dbSDimitry Andric MBBSet.erase(MBB);
1645ffd83dbSDimitry Andric for (auto &MI : *MBB) {
1655ffd83dbSDimitry Andric if (WebAssembly::isBrTable(MI)) {
166*af732203SDimitry Andric fixBrTableIndex(MI, MBB, MF);
167*af732203SDimitry Andric auto *Fixed = fixBrTableDefault(MI, MBB, MF);
1685ffd83dbSDimitry Andric if (Fixed != nullptr) {
1695ffd83dbSDimitry Andric MBBSet.erase(Fixed);
1705ffd83dbSDimitry Andric Changed = true;
1715ffd83dbSDimitry Andric }
1725ffd83dbSDimitry Andric break;
1735ffd83dbSDimitry Andric }
1745ffd83dbSDimitry Andric }
1755ffd83dbSDimitry Andric }
1765ffd83dbSDimitry Andric
1775ffd83dbSDimitry Andric if (Changed) {
1785ffd83dbSDimitry Andric // We rewrote part of the function; recompute relevant things.
1795ffd83dbSDimitry Andric MF.RenumberBlocks();
1805ffd83dbSDimitry Andric return true;
1815ffd83dbSDimitry Andric }
1825ffd83dbSDimitry Andric
1835ffd83dbSDimitry Andric return false;
1845ffd83dbSDimitry Andric }
1855ffd83dbSDimitry Andric
1865ffd83dbSDimitry Andric } // end anonymous namespace
1875ffd83dbSDimitry Andric
1885ffd83dbSDimitry Andric INITIALIZE_PASS(WebAssemblyFixBrTableDefaults, DEBUG_TYPE,
1895ffd83dbSDimitry Andric "Removes range checks and sets br_table default targets", false,
1905ffd83dbSDimitry Andric false)
1915ffd83dbSDimitry Andric
createWebAssemblyFixBrTableDefaults()1925ffd83dbSDimitry Andric FunctionPass *llvm::createWebAssemblyFixBrTableDefaults() {
1935ffd83dbSDimitry Andric return new WebAssemblyFixBrTableDefaults();
1945ffd83dbSDimitry Andric }
195