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