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