xref: /llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyMCInstLower.cpp (revision 539b2e06542f7c099885533e4472e6fb3084aa96)
1 // WebAssemblyMCInstLower.cpp - Convert WebAssembly MachineInstr to an MCInst //
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 /// This file contains code to lower WebAssembly MachineInstrs to their
11 /// corresponding MCInst records.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "WebAssemblyMCInstLower.h"
16 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
17 #include "TargetInfo/WebAssemblyTargetInfo.h"
18 #include "Utils/WebAssemblyTypeUtilities.h"
19 #include "WebAssemblyAsmPrinter.h"
20 #include "WebAssemblyMachineFunctionInfo.h"
21 #include "WebAssemblyUtilities.h"
22 #include "llvm/CodeGen/AsmPrinter.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCSymbolWasm.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/raw_ostream.h"
32 
33 using namespace llvm;
34 
35 // This disables the removal of registers when lowering into MC, as required
36 // by some current tests.
37 cl::opt<bool>
38     WasmKeepRegisters("wasm-keep-registers", cl::Hidden,
39                       cl::desc("WebAssembly: output stack registers in"
40                                " instruction output for test purposes only."),
41                       cl::init(false));
42 
43 static void removeRegisterOperands(const MachineInstr *MI, MCInst &OutMI);
44 
45 MCSymbol *
46 WebAssemblyMCInstLower::GetGlobalAddressSymbol(const MachineOperand &MO) const {
47   const GlobalValue *Global = MO.getGlobal();
48   if (!isa<Function>(Global)) {
49     auto *WasmSym = cast<MCSymbolWasm>(Printer.getSymbol(Global));
50     // If the symbol doesn't have an explicit WasmSymbolType yet and the
51     // GlobalValue is actually a WebAssembly global, then ensure the symbol is a
52     // WASM_SYMBOL_TYPE_GLOBAL.
53     if (WebAssembly::isWasmVarAddressSpace(Global->getAddressSpace()) &&
54         !WasmSym->getType()) {
55       const MachineFunction &MF = *MO.getParent()->getParent()->getParent();
56       const TargetMachine &TM = MF.getTarget();
57       const Function &CurrentFunc = MF.getFunction();
58       Type *GlobalVT = Global->getValueType();
59       SmallVector<MVT, 1> VTs;
60       computeLegalValueVTs(CurrentFunc, TM, GlobalVT, VTs);
61 
62       WebAssembly::wasmSymbolSetType(WasmSym, GlobalVT, VTs);
63     }
64     return WasmSym;
65   }
66 
67   const auto *FuncTy = cast<FunctionType>(Global->getValueType());
68   const MachineFunction &MF = *MO.getParent()->getParent()->getParent();
69   const TargetMachine &TM = MF.getTarget();
70   const Function &CurrentFunc = MF.getFunction();
71 
72   SmallVector<MVT, 1> ResultMVTs;
73   SmallVector<MVT, 4> ParamMVTs;
74   const auto *const F = dyn_cast<Function>(Global);
75   computeSignatureVTs(FuncTy, F, CurrentFunc, TM, ParamMVTs, ResultMVTs);
76   auto Signature = signatureFromMVTs(Ctx, ResultMVTs, ParamMVTs);
77 
78   bool InvokeDetected = false;
79   auto *WasmSym = Printer.getMCSymbolForFunction(
80       F, WebAssembly::WasmEnableEmEH || WebAssembly::WasmEnableEmSjLj,
81       Signature, InvokeDetected);
82   WasmSym->setSignature(Signature);
83   WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
84   return WasmSym;
85 }
86 
87 MCSymbol *WebAssemblyMCInstLower::GetExternalSymbolSymbol(
88     const MachineOperand &MO) const {
89   return Printer.getOrCreateWasmSymbol(MO.getSymbolName());
90 }
91 
92 MCOperand WebAssemblyMCInstLower::lowerSymbolOperand(const MachineOperand &MO,
93                                                      MCSymbol *Sym) const {
94   MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None;
95   unsigned TargetFlags = MO.getTargetFlags();
96 
97   switch (TargetFlags) {
98     case WebAssemblyII::MO_NO_FLAG:
99       break;
100     case WebAssemblyII::MO_GOT_TLS:
101       Kind = MCSymbolRefExpr::VK_WASM_GOT_TLS;
102       break;
103     case WebAssemblyII::MO_GOT:
104       Kind = MCSymbolRefExpr::VK_GOT;
105       break;
106     case WebAssemblyII::MO_MEMORY_BASE_REL:
107       Kind = MCSymbolRefExpr::VK_WASM_MBREL;
108       break;
109     case WebAssemblyII::MO_TLS_BASE_REL:
110       Kind = MCSymbolRefExpr::VK_WASM_TLSREL;
111       break;
112     case WebAssemblyII::MO_TABLE_BASE_REL:
113       Kind = MCSymbolRefExpr::VK_WASM_TBREL;
114       break;
115     default:
116       llvm_unreachable("Unknown target flag on GV operand");
117   }
118 
119   const MCExpr *Expr = MCSymbolRefExpr::create(Sym, Kind, Ctx);
120 
121   if (MO.getOffset() != 0) {
122     const auto *WasmSym = cast<MCSymbolWasm>(Sym);
123     if (TargetFlags == WebAssemblyII::MO_GOT)
124       report_fatal_error("GOT symbol references do not support offsets");
125     if (WasmSym->isFunction())
126       report_fatal_error("Function addresses with offsets not supported");
127     if (WasmSym->isGlobal())
128       report_fatal_error("Global indexes with offsets not supported");
129     if (WasmSym->isTag())
130       report_fatal_error("Tag indexes with offsets not supported");
131     if (WasmSym->isTable())
132       report_fatal_error("Table indexes with offsets not supported");
133 
134     Expr = MCBinaryExpr::createAdd(
135         Expr, MCConstantExpr::create(MO.getOffset(), Ctx), Ctx);
136   }
137 
138   return MCOperand::createExpr(Expr);
139 }
140 
141 MCOperand WebAssemblyMCInstLower::lowerTypeIndexOperand(
142     SmallVectorImpl<wasm::ValType> &&Returns,
143     SmallVectorImpl<wasm::ValType> &&Params) const {
144   auto Signature = Ctx.createWasmSignature();
145   Signature->Returns = std::move(Returns);
146   Signature->Params = std::move(Params);
147   MCSymbol *Sym = Printer.createTempSymbol("typeindex");
148   auto *WasmSym = cast<MCSymbolWasm>(Sym);
149   WasmSym->setSignature(Signature);
150   WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
151   const MCExpr *Expr =
152       MCSymbolRefExpr::create(WasmSym, MCSymbolRefExpr::VK_WASM_TYPEINDEX, Ctx);
153   return MCOperand::createExpr(Expr);
154 }
155 
156 static void getFunctionReturns(const MachineInstr *MI,
157                                SmallVectorImpl<wasm::ValType> &Returns) {
158   const Function &F = MI->getMF()->getFunction();
159   const TargetMachine &TM = MI->getMF()->getTarget();
160   Type *RetTy = F.getReturnType();
161   SmallVector<MVT, 4> CallerRetTys;
162   computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
163   valTypesFromMVTs(CallerRetTys, Returns);
164 }
165 
166 void WebAssemblyMCInstLower::lower(const MachineInstr *MI,
167                                    MCInst &OutMI) const {
168   OutMI.setOpcode(MI->getOpcode());
169 
170   const MCInstrDesc &Desc = MI->getDesc();
171   unsigned NumVariadicDefs = MI->getNumExplicitDefs() - Desc.getNumDefs();
172   const MachineFunction *MF = MI->getMF();
173   const auto &TLI =
174       *MF->getSubtarget<WebAssemblySubtarget>().getTargetLowering();
175   wasm::ValType PtrTy = TLI.getPointerTy(MF->getDataLayout()) == MVT::i32
176                             ? wasm::ValType::I32
177                             : wasm::ValType::I64;
178 
179   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
180     const MachineOperand &MO = MI->getOperand(I);
181 
182     MCOperand MCOp;
183     switch (MO.getType()) {
184     default:
185       MI->print(errs());
186       llvm_unreachable("unknown operand type");
187     case MachineOperand::MO_MachineBasicBlock:
188       MI->print(errs());
189       llvm_unreachable("MachineBasicBlock operand should have been rewritten");
190     case MachineOperand::MO_Register: {
191       // Ignore all implicit register operands.
192       if (MO.isImplicit())
193         continue;
194       const WebAssemblyFunctionInfo &MFI =
195           *MI->getParent()->getParent()->getInfo<WebAssemblyFunctionInfo>();
196       unsigned WAReg = MFI.getWAReg(MO.getReg());
197       MCOp = MCOperand::createReg(WAReg);
198       break;
199     }
200     case MachineOperand::MO_Immediate: {
201       unsigned DescIndex = I - NumVariadicDefs;
202       if (DescIndex < Desc.NumOperands) {
203         const MCOperandInfo &Info = Desc.operands()[DescIndex];
204         if (Info.OperandType == WebAssembly::OPERAND_TYPEINDEX) {
205           SmallVector<wasm::ValType, 4> Returns;
206           SmallVector<wasm::ValType, 4> Params;
207 
208           const MachineRegisterInfo &MRI =
209               MI->getParent()->getParent()->getRegInfo();
210           for (const MachineOperand &MO : MI->defs())
211             Returns.push_back(WebAssembly::regClassToValType(
212                 MRI.getRegClass(MO.getReg())->getID()));
213           for (const MachineOperand &MO : MI->explicit_uses())
214             if (MO.isReg())
215               Params.push_back(WebAssembly::regClassToValType(
216                   MRI.getRegClass(MO.getReg())->getID()));
217 
218           // call_indirect instructions have a callee operand at the end which
219           // doesn't count as a param.
220           if (WebAssembly::isCallIndirect(MI->getOpcode()))
221             Params.pop_back();
222 
223           // return_call_indirect instructions have the return type of the
224           // caller
225           if (MI->getOpcode() == WebAssembly::RET_CALL_INDIRECT)
226             getFunctionReturns(MI, Returns);
227 
228           MCOp = lowerTypeIndexOperand(std::move(Returns), std::move(Params));
229           break;
230         }
231         if (Info.OperandType == WebAssembly::OPERAND_SIGNATURE) {
232           auto BT = static_cast<WebAssembly::BlockType>(MO.getImm());
233           assert(BT != WebAssembly::BlockType::Invalid);
234           if (BT == WebAssembly::BlockType::Multivalue) {
235             SmallVector<wasm::ValType, 2> Returns;
236             // Multivalue blocks are emitted in two cases:
237             // 1. When the blocks will never be exited and are at the ends of
238             //    functions (see
239             //    WebAssemblyCFGStackify::fixEndsAtEndOfFunction). In this case
240             //    the exact multivalue signature can always be inferred from the
241             //    return type of the parent function.
242             // 2. (catch_ref ...) clause in try_table instruction. Currently all
243             //    tags we support (cpp_exception and c_longjmp) throws a single
244             //    pointer, so the multivalue signature for this case will be
245             //    (ptr, exnref). Having MO_CATCH_BLOCK_SIG target flags means
246             //    this is a destination of a catch_ref.
247             if (MO.getTargetFlags() == WebAssemblyII::MO_CATCH_BLOCK_SIG) {
248               Returns = {PtrTy, wasm::ValType::EXNREF};
249             } else
250               getFunctionReturns(MI, Returns);
251             MCOp = lowerTypeIndexOperand(std::move(Returns),
252                                          SmallVector<wasm::ValType, 4>());
253             break;
254           }
255         }
256       }
257       MCOp = MCOperand::createImm(MO.getImm());
258       break;
259     }
260     case MachineOperand::MO_FPImmediate: {
261       const ConstantFP *Imm = MO.getFPImm();
262       const uint64_t BitPattern =
263           Imm->getValueAPF().bitcastToAPInt().getZExtValue();
264       if (Imm->getType()->isFloatTy())
265         MCOp = MCOperand::createSFPImm(static_cast<uint32_t>(BitPattern));
266       else if (Imm->getType()->isDoubleTy())
267         MCOp = MCOperand::createDFPImm(BitPattern);
268       else
269         llvm_unreachable("unknown floating point immediate type");
270       break;
271     }
272     case MachineOperand::MO_GlobalAddress:
273       MCOp = lowerSymbolOperand(MO, GetGlobalAddressSymbol(MO));
274       break;
275     case MachineOperand::MO_ExternalSymbol:
276       MCOp = lowerSymbolOperand(MO, GetExternalSymbolSymbol(MO));
277       break;
278     case MachineOperand::MO_MCSymbol:
279       assert(MO.getTargetFlags() == 0 &&
280              "WebAssembly does not use target flags on MCSymbol");
281       MCOp = lowerSymbolOperand(MO, MO.getMCSymbol());
282       break;
283     }
284 
285     OutMI.addOperand(MCOp);
286   }
287 
288   if (!WasmKeepRegisters)
289     removeRegisterOperands(MI, OutMI);
290   else if (Desc.variadicOpsAreDefs())
291     OutMI.insert(OutMI.begin(), MCOperand::createImm(MI->getNumExplicitDefs()));
292 }
293 
294 static void removeRegisterOperands(const MachineInstr *MI, MCInst &OutMI) {
295   // Remove all uses of stackified registers to bring the instruction format
296   // into its final stack form used thruout MC, and transition opcodes to
297   // their _S variant.
298   // We do this separate from the above code that still may need these
299   // registers for e.g. call_indirect signatures.
300   // See comments in lib/Target/WebAssembly/WebAssemblyInstrFormats.td for
301   // details.
302   // TODO: the code above creates new registers which are then removed here.
303   // That code could be slightly simplified by not doing that, though maybe
304   // it is simpler conceptually to keep the code above in "register mode"
305   // until this transition point.
306   // FIXME: we are not processing inline assembly, which contains register
307   // operands, because it is used by later target generic code.
308   if (MI->isDebugInstr() || MI->isLabel() || MI->isInlineAsm())
309     return;
310 
311   // Transform to _S instruction.
312   auto RegOpcode = OutMI.getOpcode();
313   auto StackOpcode = WebAssembly::getStackOpcode(RegOpcode);
314   assert(StackOpcode != -1 && "Failed to stackify instruction");
315   OutMI.setOpcode(StackOpcode);
316 
317   // Remove register operands.
318   for (auto I = OutMI.getNumOperands(); I; --I) {
319     auto &MO = OutMI.getOperand(I - 1);
320     if (MO.isReg()) {
321       OutMI.erase(&MO);
322     }
323   }
324 }
325