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> EnableEmException;
42 extern cl::opt<bool> EnableEmSjLj;
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, EnableEmException || EnableEmSjLj, 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:
106       Kind = MCSymbolRefExpr::VK_GOT;
107       break;
108     case WebAssemblyII::MO_MEMORY_BASE_REL:
109       Kind = MCSymbolRefExpr::VK_WASM_MBREL;
110       break;
111     case WebAssemblyII::MO_TLS_BASE_REL:
112       Kind = MCSymbolRefExpr::VK_WASM_TLSREL;
113       break;
114     case WebAssemblyII::MO_TABLE_BASE_REL:
115       Kind = MCSymbolRefExpr::VK_WASM_TBREL;
116       break;
117     default:
118       llvm_unreachable("Unknown target flag on GV operand");
119   }
120 
121   const MCExpr *Expr = MCSymbolRefExpr::create(Sym, Kind, Ctx);
122 
123   if (MO.getOffset() != 0) {
124     const auto *WasmSym = cast<MCSymbolWasm>(Sym);
125     if (TargetFlags == WebAssemblyII::MO_GOT)
126       report_fatal_error("GOT symbol references do not support offsets");
127     if (WasmSym->isFunction())
128       report_fatal_error("Function addresses with offsets not supported");
129     if (WasmSym->isGlobal())
130       report_fatal_error("Global indexes with offsets not supported");
131     if (WasmSym->isTag())
132       report_fatal_error("Tag indexes with offsets not supported");
133     if (WasmSym->isTable())
134       report_fatal_error("Table indexes with offsets not supported");
135 
136     Expr = MCBinaryExpr::createAdd(
137         Expr, MCConstantExpr::create(MO.getOffset(), Ctx), Ctx);
138   }
139 
140   return MCOperand::createExpr(Expr);
141 }
142 
143 MCOperand WebAssemblyMCInstLower::lowerTypeIndexOperand(
144     SmallVector<wasm::ValType, 1> &&Returns,
145     SmallVector<wasm::ValType, 4> &&Params) const {
146   auto Signature = std::make_unique<wasm::WasmSignature>(std::move(Returns),
147                                                          std::move(Params));
148   MCSymbol *Sym = Printer.createTempSymbol("typeindex");
149   auto *WasmSym = cast<MCSymbolWasm>(Sym);
150   WasmSym->setSignature(Signature.get());
151   Printer.addSignature(std::move(Signature));
152   WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
153   const MCExpr *Expr =
154       MCSymbolRefExpr::create(WasmSym, MCSymbolRefExpr::VK_WASM_TYPEINDEX, Ctx);
155   return MCOperand::createExpr(Expr);
156 }
157 
158 // Return the WebAssembly type associated with the given register class.
159 static wasm::ValType getType(const TargetRegisterClass *RC) {
160   if (RC == &WebAssembly::I32RegClass)
161     return wasm::ValType::I32;
162   if (RC == &WebAssembly::I64RegClass)
163     return wasm::ValType::I64;
164   if (RC == &WebAssembly::F32RegClass)
165     return wasm::ValType::F32;
166   if (RC == &WebAssembly::F64RegClass)
167     return wasm::ValType::F64;
168   if (RC == &WebAssembly::V128RegClass)
169     return wasm::ValType::V128;
170   llvm_unreachable("Unexpected register class");
171 }
172 
173 static void getFunctionReturns(const MachineInstr *MI,
174                                SmallVectorImpl<wasm::ValType> &Returns) {
175   const Function &F = MI->getMF()->getFunction();
176   const TargetMachine &TM = MI->getMF()->getTarget();
177   Type *RetTy = F.getReturnType();
178   SmallVector<MVT, 4> CallerRetTys;
179   computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
180   valTypesFromMVTs(CallerRetTys, Returns);
181 }
182 
183 void WebAssemblyMCInstLower::lower(const MachineInstr *MI,
184                                    MCInst &OutMI) const {
185   OutMI.setOpcode(MI->getOpcode());
186 
187   const MCInstrDesc &Desc = MI->getDesc();
188   unsigned NumVariadicDefs = MI->getNumExplicitDefs() - Desc.getNumDefs();
189   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
190     const MachineOperand &MO = MI->getOperand(I);
191 
192     MCOperand MCOp;
193     switch (MO.getType()) {
194     default:
195       MI->print(errs());
196       llvm_unreachable("unknown operand type");
197     case MachineOperand::MO_MachineBasicBlock:
198       MI->print(errs());
199       llvm_unreachable("MachineBasicBlock operand should have been rewritten");
200     case MachineOperand::MO_Register: {
201       // Ignore all implicit register operands.
202       if (MO.isImplicit())
203         continue;
204       const WebAssemblyFunctionInfo &MFI =
205           *MI->getParent()->getParent()->getInfo<WebAssemblyFunctionInfo>();
206       unsigned WAReg = MFI.getWAReg(MO.getReg());
207       MCOp = MCOperand::createReg(WAReg);
208       break;
209     }
210     case MachineOperand::MO_Immediate: {
211       unsigned DescIndex = I - NumVariadicDefs;
212       if (DescIndex < Desc.NumOperands) {
213         const MCOperandInfo &Info = Desc.OpInfo[DescIndex];
214         if (Info.OperandType == WebAssembly::OPERAND_TYPEINDEX) {
215           SmallVector<wasm::ValType, 4> Returns;
216           SmallVector<wasm::ValType, 4> Params;
217 
218           const MachineRegisterInfo &MRI =
219               MI->getParent()->getParent()->getRegInfo();
220           for (const MachineOperand &MO : MI->defs())
221             Returns.push_back(getType(MRI.getRegClass(MO.getReg())));
222           for (const MachineOperand &MO : MI->explicit_uses())
223             if (MO.isReg())
224               Params.push_back(getType(MRI.getRegClass(MO.getReg())));
225 
226           // call_indirect instructions have a callee operand at the end which
227           // doesn't count as a param.
228           if (WebAssembly::isCallIndirect(MI->getOpcode()))
229             Params.pop_back();
230 
231           // return_call_indirect instructions have the return type of the
232           // caller
233           if (MI->getOpcode() == WebAssembly::RET_CALL_INDIRECT)
234             getFunctionReturns(MI, Returns);
235 
236           MCOp = lowerTypeIndexOperand(std::move(Returns), std::move(Params));
237           break;
238         } else if (Info.OperandType == WebAssembly::OPERAND_SIGNATURE) {
239           auto BT = static_cast<WebAssembly::BlockType>(MO.getImm());
240           assert(BT != WebAssembly::BlockType::Invalid);
241           if (BT == WebAssembly::BlockType::Multivalue) {
242             SmallVector<wasm::ValType, 1> Returns;
243             getFunctionReturns(MI, Returns);
244             MCOp = lowerTypeIndexOperand(std::move(Returns),
245                                          SmallVector<wasm::ValType, 4>());
246             break;
247           }
248         } else if (Info.OperandType == WebAssembly::OPERAND_HEAPTYPE) {
249           assert(static_cast<WebAssembly::HeapType>(MO.getImm()) !=
250                  WebAssembly::HeapType::Invalid);
251           // With typed function references, this will need a case for type
252           // index operands.  Otherwise, fall through.
253         }
254       }
255       MCOp = MCOperand::createImm(MO.getImm());
256       break;
257     }
258     case MachineOperand::MO_FPImmediate: {
259       const ConstantFP *Imm = MO.getFPImm();
260       const uint64_t BitPattern =
261           Imm->getValueAPF().bitcastToAPInt().getZExtValue();
262       if (Imm->getType()->isFloatTy())
263         MCOp = MCOperand::createSFPImm(static_cast<uint32_t>(BitPattern));
264       else if (Imm->getType()->isDoubleTy())
265         MCOp = MCOperand::createDFPImm(BitPattern);
266       else
267         llvm_unreachable("unknown floating point immediate type");
268       break;
269     }
270     case MachineOperand::MO_GlobalAddress:
271       MCOp = lowerSymbolOperand(MO, GetGlobalAddressSymbol(MO));
272       break;
273     case MachineOperand::MO_ExternalSymbol:
274       // The target flag indicates whether this is a symbol for a
275       // variable or a function.
276       assert(MO.getTargetFlags() == 0 &&
277              "WebAssembly uses only symbol flags on ExternalSymbols");
278       MCOp = lowerSymbolOperand(MO, GetExternalSymbolSymbol(MO));
279       break;
280     case MachineOperand::MO_MCSymbol:
281       // This is currently used only for LSDA symbols (GCC_except_table),
282       // because global addresses or other external symbols are handled above.
283       assert(MO.getTargetFlags() == 0 &&
284              "WebAssembly does not use target flags on MCSymbol");
285       MCOp = lowerSymbolOperand(MO, MO.getMCSymbol());
286       break;
287     }
288 
289     OutMI.addOperand(MCOp);
290   }
291 
292   if (!WasmKeepRegisters)
293     removeRegisterOperands(MI, OutMI);
294   else if (Desc.variadicOpsAreDefs())
295     OutMI.insert(OutMI.begin(), MCOperand::createImm(MI->getNumExplicitDefs()));
296 }
297 
298 static void removeRegisterOperands(const MachineInstr *MI, MCInst &OutMI) {
299   // Remove all uses of stackified registers to bring the instruction format
300   // into its final stack form used thruout MC, and transition opcodes to
301   // their _S variant.
302   // We do this separate from the above code that still may need these
303   // registers for e.g. call_indirect signatures.
304   // See comments in lib/Target/WebAssembly/WebAssemblyInstrFormats.td for
305   // details.
306   // TODO: the code above creates new registers which are then removed here.
307   // That code could be slightly simplified by not doing that, though maybe
308   // it is simpler conceptually to keep the code above in "register mode"
309   // until this transition point.
310   // FIXME: we are not processing inline assembly, which contains register
311   // operands, because it is used by later target generic code.
312   if (MI->isDebugInstr() || MI->isLabel() || MI->isInlineAsm())
313     return;
314 
315   // Transform to _S instruction.
316   auto RegOpcode = OutMI.getOpcode();
317   auto StackOpcode = WebAssembly::getStackOpcode(RegOpcode);
318   assert(StackOpcode != -1 && "Failed to stackify instruction");
319   OutMI.setOpcode(StackOpcode);
320 
321   // Remove register operands.
322   for (auto I = OutMI.getNumOperands(); I; --I) {
323     auto &MO = OutMI.getOperand(I - 1);
324     if (MO.isReg()) {
325       OutMI.erase(&MO);
326     }
327   }
328 }
329