LLVM 24.0.0git
WebAssemblyFixBrTableDefaults.cpp
Go to the documentation of this file.
1//=- WebAssemblyFixBrTableDefaults.cpp - Fix br_table default branch targets -//
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 This file implements a pass that eliminates redundant range checks
10/// guarding br_table instructions. Since jump tables on most targets cannot
11/// handle out of range indices, LLVM emits these checks before most jump
12/// tables. But br_table takes a default branch target as an argument, so it
13/// does not need the range checks.
14///
15//===----------------------------------------------------------------------===//
16
18#include "WebAssembly.h"
25#include "llvm/IR/Analysis.h"
26#include "llvm/Pass.h"
27
28using namespace llvm;
29
30#define DEBUG_TYPE "wasm-fix-br-table-defaults"
31
32namespace {
33
34class WebAssemblyFixBrTableDefaultsLegacy final : public MachineFunctionPass {
35 StringRef getPassName() const override {
36 return "WebAssembly Fix br_table Defaults";
37 }
38
39 bool runOnMachineFunction(MachineFunction &MF) override;
40
41public:
42 static char ID; // Pass identification, replacement for typeid
43 WebAssemblyFixBrTableDefaultsLegacy() : MachineFunctionPass(ID) {}
44};
45
46char WebAssemblyFixBrTableDefaultsLegacy::ID = 0;
47
48// Target independent selection dag assumes that it is ok to use PointerTy
49// as the index for a "switch", whereas Wasm so far only has a 32-bit br_table.
50// See e.g. SelectionDAGBuilder::visitJumpTableHeader
51// We have a 64-bit br_table in the tablegen defs as a result, which does get
52// selected, and thus we get incorrect truncates/extensions happening on
53// wasm64. Here we fix that.
54void fixBrTableIndex(MachineInstr &MI, MachineBasicBlock *MBB,
55 MachineFunction &MF) {
56 // Only happens on wasm64.
57 auto &WST = MF.getSubtarget<WebAssemblySubtarget>();
58 if (!WST.hasAddr64())
59 return;
60
61 assert(MI.getDesc().getOpcode() == WebAssembly::BR_TABLE_I64 &&
62 "64-bit br_table pseudo instruction expected");
63
64 // Find extension op, if any. It sits in the previous BB before the branch.
65 auto ExtMI = MF.getRegInfo().getVRegDef(MI.getOperand(0).getReg());
66 if (ExtMI->getOpcode() == WebAssembly::I64_EXTEND_U_I32) {
67 // Unnecessarily extending a 32-bit value to 64, remove it.
68 auto ExtDefReg = ExtMI->getOperand(0).getReg();
69 assert(MI.getOperand(0).getReg() == ExtDefReg);
70 MI.getOperand(0).setReg(ExtMI->getOperand(1).getReg());
71 if (MF.getRegInfo().use_nodbg_empty(ExtDefReg)) {
72 // No more users of extend, delete it.
73 ExtMI->eraseFromParent();
74 }
75 } else {
76 // Incoming 64-bit value that needs to be truncated.
77 Register Reg32 =
78 MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass);
79 BuildMI(*MBB, MI.getIterator(), MI.getDebugLoc(),
80 WST.getInstrInfo()->get(WebAssembly::I32_WRAP_I64), Reg32)
81 .addReg(MI.getOperand(0).getReg());
82 MI.getOperand(0).setReg(Reg32);
83 }
84
85 // We now have a 32-bit operand in all cases, so change the instruction
86 // accordingly.
87 MI.setDesc(WST.getInstrInfo()->get(WebAssembly::BR_TABLE_I32));
88}
89
90// `MI` is a br_table instruction with a dummy default target argument. This
91// function finds and adds the default target argument and removes any redundant
92// range check preceding the br_table. Returns the MBB that the br_table is
93// moved into so it can be removed from further consideration, or nullptr if the
94// br_table cannot be optimized.
96 MachineFunction &MF) {
97 // Get the header block, which contains the redundant range check.
98 assert(MBB->pred_size() == 1 && "Expected a single guard predecessor");
99 auto *HeaderMBB = *MBB->pred_begin();
100
101 // Find the conditional jump to the default target. If it doesn't exist, the
102 // default target is unreachable anyway, so we can keep the existing dummy
103 // target.
104 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
106 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
107 bool Analyzed = !TII.analyzeBranch(*HeaderMBB, TBB, FBB, Cond);
108 assert(Analyzed && "Could not analyze jump header branches");
109 (void)Analyzed;
110
111 // Here are the possible outcomes. '_' is nullptr, `J` is the jump table block
112 // aka MBB, 'D' is the default block.
113 //
114 // TBB | FBB | Meaning
115 // _ | _ | No default block, header falls through to jump table
116 // J | _ | No default block, header jumps to the jump table
117 // D | _ | Header jumps to the default and falls through to the jump table
118 // D | J | Header jumps to the default and also to the jump table
119 if (TBB && TBB != MBB) {
120 assert((FBB == nullptr || FBB == MBB) &&
121 "Expected jump or fallthrough to br_table block");
122 assert(Cond.size() == 2 && Cond[1].isReg() && "Unexpected condition info");
123
124 // If the range check checks an i64 value, we cannot optimize it out because
125 // the i64 index is truncated to an i32, making values over 2^32
126 // indistinguishable from small numbers. There are also other strange edge
127 // cases that can arise in practice that we don't want to reason about, so
128 // conservatively only perform the optimization if the range check is the
129 // normal case of an i32.gt_u.
131 auto *RangeCheck = MRI.getVRegDef(Cond[1].getReg());
132 assert(RangeCheck != nullptr);
133 if (RangeCheck->getOpcode() != WebAssembly::GT_U_I32)
134 return nullptr;
135
136 // Remove the dummy default target and install the real one.
137 MI.removeOperand(MI.getNumExplicitOperands() - 1);
138 MI.addOperand(MF, MachineOperand::CreateMBB(TBB));
139 }
140
141 // Remove any branches from the header and splice in the jump table instead
142 TII.removeBranch(*HeaderMBB, nullptr);
143 HeaderMBB->splice(HeaderMBB->end(), MBB, MBB->begin(), MBB->end());
144
145 // Update CFG to skip the old jump table block. Remove shared successors
146 // before transferring to avoid duplicated successors.
147 HeaderMBB->removeSuccessor(MBB);
148 for (auto &Succ : MBB->successors())
149 if (HeaderMBB->isSuccessor(Succ))
150 HeaderMBB->removeSuccessor(Succ);
151 HeaderMBB->transferSuccessorsAndUpdatePHIs(MBB);
152
153 // Remove the old jump table block from the function
154 MF.erase(MBB);
155
156 return HeaderMBB;
157}
158
159bool fixBrTableDefaults(MachineFunction &MF) {
160 LLVM_DEBUG(dbgs() << "********** Fixing br_table Default Targets **********\n"
161 "********** Function: "
162 << MF.getName() << '\n');
163
164 bool Changed = false;
167 MBBSet;
168 for (auto &MBB : MF)
169 MBBSet.insert(&MBB);
170
171 while (!MBBSet.empty()) {
172 MachineBasicBlock *MBB = *MBBSet.begin();
173 MBBSet.remove(MBB);
174 for (auto &MI : *MBB) {
175 if (WebAssembly::isBrTable(MI.getOpcode())) {
176 fixBrTableIndex(MI, MBB, MF);
177 auto *Fixed = fixBrTableDefault(MI, MBB, MF);
178 if (Fixed != nullptr) {
179 MBBSet.remove(Fixed);
180 Changed = true;
181 }
182 break;
183 }
184 }
185 }
186
187 if (Changed) {
188 // We rewrote part of the function; recompute relevant things.
189 MF.RenumberBlocks();
190 return true;
191 }
192
193 return false;
194}
195
196} // end anonymous namespace
197
198INITIALIZE_PASS(WebAssemblyFixBrTableDefaultsLegacy, DEBUG_TYPE,
199 "Removes range checks and sets br_table default targets", false,
200 false)
201
203 return new WebAssemblyFixBrTableDefaultsLegacy();
204}
205
206bool WebAssemblyFixBrTableDefaultsLegacy::runOnMachineFunction(
207 MachineFunction &MF) {
208 return fixBrTableDefaults(MF);
209}
210
211PreservedAnalyses
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
#define LLVM_DEBUG(...)
Definition Debug.h:119
This file provides WebAssembly-specific target descriptions.
This file declares the WebAssembly-specific subclass of TargetSubtarget.
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end.
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
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.
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them.
void erase(iterator MBBI)
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
static MachineOperand CreateMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
A vector that has set insertion semantics.
Definition SetVector.h:57
bool remove(const value_type &X)
Remove an item from the set vector.
Definition SetVector.h:181
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
iterator begin()
Get an iterator to the beginning of the SetVector.
Definition SetVector.h:106
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
bool isBrTable(unsigned Opc)
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
FunctionPass * createWebAssemblyFixBrTableDefaultsLegacyPass()