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 *
GetGlobalAddressSymbol(const MachineOperand & MO) const47 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 
GetExternalSymbolSymbol(const MachineOperand & MO) const92 MCSymbol *WebAssemblyMCInstLower::GetExternalSymbolSymbol(
93     const MachineOperand &MO) const {
94   return Printer.getOrCreateWasmSymbol(MO.getSymbolName());
95 }
96 
lowerSymbolOperand(const MachineOperand & MO,MCSymbol * Sym) const97 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 
lowerTypeIndexOperand(SmallVector<wasm::ValType,1> && Returns,SmallVector<wasm::ValType,4> && Params) const143 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.
getType(const TargetRegisterClass * RC)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   if (RC == &WebAssembly::EXTERNREFRegClass)
171     return wasm::ValType::EXTERNREF;
172   if (RC == &WebAssembly::FUNCREFRegClass)
173     return wasm::ValType::FUNCREF;
174   llvm_unreachable("Unexpected register class");
175 }
176 
getFunctionReturns(const MachineInstr * MI,SmallVectorImpl<wasm::ValType> & Returns)177 static void getFunctionReturns(const MachineInstr *MI,
178                                SmallVectorImpl<wasm::ValType> &Returns) {
179   const Function &F = MI->getMF()->getFunction();
180   const TargetMachine &TM = MI->getMF()->getTarget();
181   Type *RetTy = F.getReturnType();
182   SmallVector<MVT, 4> CallerRetTys;
183   computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
184   valTypesFromMVTs(CallerRetTys, Returns);
185 }
186 
lower(const MachineInstr * MI,MCInst & OutMI) const187 void WebAssemblyMCInstLower::lower(const MachineInstr *MI,
188                                    MCInst &OutMI) const {
189   OutMI.setOpcode(MI->getOpcode());
190 
191   const MCInstrDesc &Desc = MI->getDesc();
192   unsigned NumVariadicDefs = MI->getNumExplicitDefs() - Desc.getNumDefs();
193   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
194     const MachineOperand &MO = MI->getOperand(I);
195 
196     MCOperand MCOp;
197     switch (MO.getType()) {
198     default:
199       MI->print(errs());
200       llvm_unreachable("unknown operand type");
201     case MachineOperand::MO_MachineBasicBlock:
202       MI->print(errs());
203       llvm_unreachable("MachineBasicBlock operand should have been rewritten");
204     case MachineOperand::MO_Register: {
205       // Ignore all implicit register operands.
206       if (MO.isImplicit())
207         continue;
208       const WebAssemblyFunctionInfo &MFI =
209           *MI->getParent()->getParent()->getInfo<WebAssemblyFunctionInfo>();
210       unsigned WAReg = MFI.getWAReg(MO.getReg());
211       MCOp = MCOperand::createReg(WAReg);
212       break;
213     }
214     case MachineOperand::MO_Immediate: {
215       unsigned DescIndex = I - NumVariadicDefs;
216       if (DescIndex < Desc.NumOperands) {
217         const MCOperandInfo &Info = Desc.OpInfo[DescIndex];
218         if (Info.OperandType == WebAssembly::OPERAND_TYPEINDEX) {
219           SmallVector<wasm::ValType, 4> Returns;
220           SmallVector<wasm::ValType, 4> Params;
221 
222           const MachineRegisterInfo &MRI =
223               MI->getParent()->getParent()->getRegInfo();
224           for (const MachineOperand &MO : MI->defs())
225             Returns.push_back(getType(MRI.getRegClass(MO.getReg())));
226           for (const MachineOperand &MO : MI->explicit_uses())
227             if (MO.isReg())
228               Params.push_back(getType(MRI.getRegClass(MO.getReg())));
229 
230           // call_indirect instructions have a callee operand at the end which
231           // doesn't count as a param.
232           if (WebAssembly::isCallIndirect(MI->getOpcode()))
233             Params.pop_back();
234 
235           // return_call_indirect instructions have the return type of the
236           // caller
237           if (MI->getOpcode() == WebAssembly::RET_CALL_INDIRECT)
238             getFunctionReturns(MI, Returns);
239 
240           MCOp = lowerTypeIndexOperand(std::move(Returns), std::move(Params));
241           break;
242         } else if (Info.OperandType == WebAssembly::OPERAND_SIGNATURE) {
243           auto BT = static_cast<WebAssembly::BlockType>(MO.getImm());
244           assert(BT != WebAssembly::BlockType::Invalid);
245           if (BT == WebAssembly::BlockType::Multivalue) {
246             SmallVector<wasm::ValType, 1> Returns;
247             getFunctionReturns(MI, Returns);
248             MCOp = lowerTypeIndexOperand(std::move(Returns),
249                                          SmallVector<wasm::ValType, 4>());
250             break;
251           }
252         } else if (Info.OperandType == WebAssembly::OPERAND_HEAPTYPE) {
253           assert(static_cast<WebAssembly::HeapType>(MO.getImm()) !=
254                  WebAssembly::HeapType::Invalid);
255           // With typed function references, this will need a case for type
256           // index operands.  Otherwise, fall through.
257         }
258       }
259       MCOp = MCOperand::createImm(MO.getImm());
260       break;
261     }
262     case MachineOperand::MO_FPImmediate: {
263       const ConstantFP *Imm = MO.getFPImm();
264       const uint64_t BitPattern =
265           Imm->getValueAPF().bitcastToAPInt().getZExtValue();
266       if (Imm->getType()->isFloatTy())
267         MCOp = MCOperand::createSFPImm(static_cast<uint32_t>(BitPattern));
268       else if (Imm->getType()->isDoubleTy())
269         MCOp = MCOperand::createDFPImm(BitPattern);
270       else
271         llvm_unreachable("unknown floating point immediate type");
272       break;
273     }
274     case MachineOperand::MO_GlobalAddress:
275       MCOp = lowerSymbolOperand(MO, GetGlobalAddressSymbol(MO));
276       break;
277     case MachineOperand::MO_ExternalSymbol:
278       // The target flag indicates whether this is a symbol for a
279       // variable or a function.
280       assert(MO.getTargetFlags() == 0 &&
281              "WebAssembly uses only symbol flags on ExternalSymbols");
282       MCOp = lowerSymbolOperand(MO, GetExternalSymbolSymbol(MO));
283       break;
284     case MachineOperand::MO_MCSymbol:
285       // This is currently used only for LSDA symbols (GCC_except_table),
286       // because global addresses or other external symbols are handled above.
287       assert(MO.getTargetFlags() == 0 &&
288              "WebAssembly does not use target flags on MCSymbol");
289       MCOp = lowerSymbolOperand(MO, MO.getMCSymbol());
290       break;
291     }
292 
293     OutMI.addOperand(MCOp);
294   }
295 
296   if (!WasmKeepRegisters)
297     removeRegisterOperands(MI, OutMI);
298   else if (Desc.variadicOpsAreDefs())
299     OutMI.insert(OutMI.begin(), MCOperand::createImm(MI->getNumExplicitDefs()));
300 }
301 
removeRegisterOperands(const MachineInstr * MI,MCInst & OutMI)302 static void removeRegisterOperands(const MachineInstr *MI, MCInst &OutMI) {
303   // Remove all uses of stackified registers to bring the instruction format
304   // into its final stack form used thruout MC, and transition opcodes to
305   // their _S variant.
306   // We do this separate from the above code that still may need these
307   // registers for e.g. call_indirect signatures.
308   // See comments in lib/Target/WebAssembly/WebAssemblyInstrFormats.td for
309   // details.
310   // TODO: the code above creates new registers which are then removed here.
311   // That code could be slightly simplified by not doing that, though maybe
312   // it is simpler conceptually to keep the code above in "register mode"
313   // until this transition point.
314   // FIXME: we are not processing inline assembly, which contains register
315   // operands, because it is used by later target generic code.
316   if (MI->isDebugInstr() || MI->isLabel() || MI->isInlineAsm())
317     return;
318 
319   // Transform to _S instruction.
320   auto RegOpcode = OutMI.getOpcode();
321   auto StackOpcode = WebAssembly::getStackOpcode(RegOpcode);
322   assert(StackOpcode != -1 && "Failed to stackify instruction");
323   OutMI.setOpcode(StackOpcode);
324 
325   // Remove register operands.
326   for (auto I = OutMI.getNumOperands(); I; --I) {
327     auto &MO = OutMI.getOperand(I - 1);
328     if (MO.isReg()) {
329       OutMI.erase(&MO);
330     }
331   }
332 }
333