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 "WebAssemblyAsmPrinter.h"
19 #include "WebAssemblyMachineFunctionInfo.h"
20 #include "WebAssemblyRuntimeLibcallSignatures.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 static void removeRegisterOperands(const MachineInstr *MI, MCInst &OutMI);
42 
43 MCSymbol *
44 WebAssemblyMCInstLower::GetGlobalAddressSymbol(const MachineOperand &MO) const {
45   const GlobalValue *Global = MO.getGlobal();
46   auto *WasmSym = cast<MCSymbolWasm>(Printer.getSymbol(Global));
47 
48   if (const auto *FuncTy = dyn_cast<FunctionType>(Global->getValueType())) {
49     const MachineFunction &MF = *MO.getParent()->getParent()->getParent();
50     const TargetMachine &TM = MF.getTarget();
51     const Function &CurrentFunc = MF.getFunction();
52 
53     SmallVector<MVT, 1> ResultMVTs;
54     SmallVector<MVT, 4> ParamMVTs;
55     const auto *const F = dyn_cast<Function>(Global);
56     computeSignatureVTs(FuncTy, F, CurrentFunc, TM, ParamMVTs, ResultMVTs);
57 
58     auto Signature = signatureFromMVTs(ResultMVTs, ParamMVTs);
59     WasmSym->setSignature(Signature.get());
60     Printer.addSignature(std::move(Signature));
61     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
62   }
63 
64   return WasmSym;
65 }
66 
67 MCSymbol *WebAssemblyMCInstLower::GetExternalSymbolSymbol(
68     const MachineOperand &MO) const {
69   const char *Name = MO.getSymbolName();
70   auto *WasmSym = cast<MCSymbolWasm>(Printer.GetExternalSymbolSymbol(Name));
71   const WebAssemblySubtarget &Subtarget = Printer.getSubtarget();
72 
73   // Except for certain known symbols, all symbols used by CodeGen are
74   // functions. It's OK to hardcode knowledge of specific symbols here; this
75   // method is precisely there for fetching the signatures of known
76   // Clang-provided symbols.
77   if (strcmp(Name, "__stack_pointer") == 0 || strcmp(Name, "__tls_base") == 0 ||
78       strcmp(Name, "__memory_base") == 0 || strcmp(Name, "__table_base") == 0 ||
79       strcmp(Name, "__tls_size") == 0 || strcmp(Name, "__tls_align") == 0) {
80     bool Mutable =
81         strcmp(Name, "__stack_pointer") == 0 || strcmp(Name, "__tls_base") == 0;
82     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
83     WasmSym->setGlobalType(wasm::WasmGlobalType{
84         uint8_t(Subtarget.hasAddr64() ? wasm::WASM_TYPE_I64
85                                       : wasm::WASM_TYPE_I32),
86         Mutable});
87     return WasmSym;
88   }
89 
90   SmallVector<wasm::ValType, 4> Returns;
91   SmallVector<wasm::ValType, 4> Params;
92   if (strcmp(Name, "__cpp_exception") == 0) {
93     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_EVENT);
94     // We can't confirm its signature index for now because there can be
95     // imported exceptions. Set it to be 0 for now.
96     WasmSym->setEventType(
97         {wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION, /* SigIndex */ 0});
98     // We may have multiple C++ compilation units to be linked together, each of
99     // which defines the exception symbol. To resolve them, we declare them as
100     // weak.
101     WasmSym->setWeak(true);
102     WasmSym->setExternal(true);
103 
104     // All C++ exceptions are assumed to have a single i32 (for wasm32) or i64
105     // (for wasm64) param type and void return type. The reaon is, all C++
106     // exception values are pointers, and to share the type section with
107     // functions, exceptions are assumed to have void return type.
108     Params.push_back(Subtarget.hasAddr64() ? wasm::ValType::I64
109                                            : wasm::ValType::I32);
110   } else { // Function symbols
111     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
112     getLibcallSignature(Subtarget, Name, Returns, Params);
113   }
114   auto Signature =
115       std::make_unique<wasm::WasmSignature>(std::move(Returns), std::move(Params));
116   WasmSym->setSignature(Signature.get());
117   Printer.addSignature(std::move(Signature));
118 
119   return WasmSym;
120 }
121 
122 MCOperand WebAssemblyMCInstLower::lowerSymbolOperand(const MachineOperand &MO,
123                                                      MCSymbol *Sym) const {
124   MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None;
125   unsigned TargetFlags = MO.getTargetFlags();
126 
127   switch (TargetFlags) {
128     case WebAssemblyII::MO_NO_FLAG:
129       break;
130     case WebAssemblyII::MO_GOT:
131       Kind = MCSymbolRefExpr::VK_GOT;
132       break;
133     case WebAssemblyII::MO_MEMORY_BASE_REL:
134       Kind = MCSymbolRefExpr::VK_WASM_MBREL;
135       break;
136     case WebAssemblyII::MO_TABLE_BASE_REL:
137       Kind = MCSymbolRefExpr::VK_WASM_TBREL;
138       break;
139     default:
140       llvm_unreachable("Unknown target flag on GV operand");
141   }
142 
143   const MCExpr *Expr = MCSymbolRefExpr::create(Sym, Kind, Ctx);
144 
145   if (MO.getOffset() != 0) {
146     const auto *WasmSym = cast<MCSymbolWasm>(Sym);
147     if (TargetFlags == WebAssemblyII::MO_GOT)
148       report_fatal_error("GOT symbol references do not support offsets");
149     if (WasmSym->isFunction())
150       report_fatal_error("Function addresses with offsets not supported");
151     if (WasmSym->isGlobal())
152       report_fatal_error("Global indexes with offsets not supported");
153     if (WasmSym->isEvent())
154       report_fatal_error("Event indexes with offsets not supported");
155 
156     Expr = MCBinaryExpr::createAdd(
157         Expr, MCConstantExpr::create(MO.getOffset(), Ctx), Ctx);
158   }
159 
160   return MCOperand::createExpr(Expr);
161 }
162 
163 MCOperand WebAssemblyMCInstLower::lowerTypeIndexOperand(
164     SmallVector<wasm::ValType, 1> &&Returns,
165     SmallVector<wasm::ValType, 4> &&Params) const {
166   auto Signature = std::make_unique<wasm::WasmSignature>(std::move(Returns),
167                                                          std::move(Params));
168   MCSymbol *Sym = Printer.createTempSymbol("typeindex");
169   auto *WasmSym = cast<MCSymbolWasm>(Sym);
170   WasmSym->setSignature(Signature.get());
171   Printer.addSignature(std::move(Signature));
172   WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
173   const MCExpr *Expr =
174       MCSymbolRefExpr::create(WasmSym, MCSymbolRefExpr::VK_WASM_TYPEINDEX, Ctx);
175   return MCOperand::createExpr(Expr);
176 }
177 
178 // Return the WebAssembly type associated with the given register class.
179 static wasm::ValType getType(const TargetRegisterClass *RC) {
180   if (RC == &WebAssembly::I32RegClass)
181     return wasm::ValType::I32;
182   if (RC == &WebAssembly::I64RegClass)
183     return wasm::ValType::I64;
184   if (RC == &WebAssembly::F32RegClass)
185     return wasm::ValType::F32;
186   if (RC == &WebAssembly::F64RegClass)
187     return wasm::ValType::F64;
188   if (RC == &WebAssembly::V128RegClass)
189     return wasm::ValType::V128;
190   llvm_unreachable("Unexpected register class");
191 }
192 
193 static void getFunctionReturns(const MachineInstr *MI,
194                                SmallVectorImpl<wasm::ValType> &Returns) {
195   const Function &F = MI->getMF()->getFunction();
196   const TargetMachine &TM = MI->getMF()->getTarget();
197   Type *RetTy = F.getReturnType();
198   SmallVector<MVT, 4> CallerRetTys;
199   computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
200   valTypesFromMVTs(CallerRetTys, Returns);
201 }
202 
203 void WebAssemblyMCInstLower::lower(const MachineInstr *MI,
204                                    MCInst &OutMI) const {
205   OutMI.setOpcode(MI->getOpcode());
206 
207   const MCInstrDesc &Desc = MI->getDesc();
208   unsigned NumVariadicDefs = MI->getNumExplicitDefs() - Desc.getNumDefs();
209   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
210     const MachineOperand &MO = MI->getOperand(I);
211 
212     MCOperand MCOp;
213     switch (MO.getType()) {
214     default:
215       MI->print(errs());
216       llvm_unreachable("unknown operand type");
217     case MachineOperand::MO_MachineBasicBlock:
218       MI->print(errs());
219       llvm_unreachable("MachineBasicBlock operand should have been rewritten");
220     case MachineOperand::MO_Register: {
221       // Ignore all implicit register operands.
222       if (MO.isImplicit())
223         continue;
224       const WebAssemblyFunctionInfo &MFI =
225           *MI->getParent()->getParent()->getInfo<WebAssemblyFunctionInfo>();
226       unsigned WAReg = MFI.getWAReg(MO.getReg());
227       MCOp = MCOperand::createReg(WAReg);
228       break;
229     }
230     case MachineOperand::MO_Immediate: {
231       unsigned DescIndex = I - NumVariadicDefs;
232       if (DescIndex < Desc.NumOperands) {
233         const MCOperandInfo &Info = Desc.OpInfo[DescIndex];
234         if (Info.OperandType == WebAssembly::OPERAND_TYPEINDEX) {
235           SmallVector<wasm::ValType, 4> Returns;
236           SmallVector<wasm::ValType, 4> Params;
237 
238           const MachineRegisterInfo &MRI =
239               MI->getParent()->getParent()->getRegInfo();
240           for (const MachineOperand &MO : MI->defs())
241             Returns.push_back(getType(MRI.getRegClass(MO.getReg())));
242           for (const MachineOperand &MO : MI->explicit_uses())
243             if (MO.isReg())
244               Params.push_back(getType(MRI.getRegClass(MO.getReg())));
245 
246           // call_indirect instructions have a callee operand at the end which
247           // doesn't count as a param.
248           if (WebAssembly::isCallIndirect(MI->getOpcode()))
249             Params.pop_back();
250 
251           // return_call_indirect instructions have the return type of the
252           // caller
253           if (MI->getOpcode() == WebAssembly::RET_CALL_INDIRECT)
254             getFunctionReturns(MI, Returns);
255 
256           MCOp = lowerTypeIndexOperand(std::move(Returns), std::move(Params));
257           break;
258         } else if (Info.OperandType == WebAssembly::OPERAND_SIGNATURE) {
259           auto BT = static_cast<WebAssembly::BlockType>(MO.getImm());
260           assert(BT != WebAssembly::BlockType::Invalid);
261           if (BT == WebAssembly::BlockType::Multivalue) {
262             SmallVector<wasm::ValType, 1> Returns;
263             getFunctionReturns(MI, Returns);
264             MCOp = lowerTypeIndexOperand(std::move(Returns),
265                                          SmallVector<wasm::ValType, 4>());
266             break;
267           }
268         }
269       }
270       MCOp = MCOperand::createImm(MO.getImm());
271       break;
272     }
273     case MachineOperand::MO_FPImmediate: {
274       // TODO: MC converts all floating point immediate operands to double.
275       // This is fine for numeric values, but may cause NaNs to change bits.
276       const ConstantFP *Imm = MO.getFPImm();
277       if (Imm->getType()->isFloatTy())
278         MCOp = MCOperand::createFPImm(Imm->getValueAPF().convertToFloat());
279       else if (Imm->getType()->isDoubleTy())
280         MCOp = MCOperand::createFPImm(Imm->getValueAPF().convertToDouble());
281       else
282         llvm_unreachable("unknown floating point immediate type");
283       break;
284     }
285     case MachineOperand::MO_GlobalAddress:
286       MCOp = lowerSymbolOperand(MO, GetGlobalAddressSymbol(MO));
287       break;
288     case MachineOperand::MO_ExternalSymbol:
289       // The target flag indicates whether this is a symbol for a
290       // variable or a function.
291       assert(MO.getTargetFlags() == 0 &&
292              "WebAssembly uses only symbol flags on ExternalSymbols");
293       MCOp = lowerSymbolOperand(MO, GetExternalSymbolSymbol(MO));
294       break;
295     case MachineOperand::MO_MCSymbol:
296       // This is currently used only for LSDA symbols (GCC_except_table),
297       // because global addresses or other external symbols are handled above.
298       assert(MO.getTargetFlags() == 0 &&
299              "WebAssembly does not use target flags on MCSymbol");
300       MCOp = lowerSymbolOperand(MO, MO.getMCSymbol());
301       break;
302     }
303 
304     OutMI.addOperand(MCOp);
305   }
306 
307   if (!WasmKeepRegisters)
308     removeRegisterOperands(MI, OutMI);
309   else if (Desc.variadicOpsAreDefs())
310     OutMI.insert(OutMI.begin(), MCOperand::createImm(MI->getNumExplicitDefs()));
311 }
312 
313 static void removeRegisterOperands(const MachineInstr *MI, MCInst &OutMI) {
314   // Remove all uses of stackified registers to bring the instruction format
315   // into its final stack form used thruout MC, and transition opcodes to
316   // their _S variant.
317   // We do this separate from the above code that still may need these
318   // registers for e.g. call_indirect signatures.
319   // See comments in lib/Target/WebAssembly/WebAssemblyInstrFormats.td for
320   // details.
321   // TODO: the code above creates new registers which are then removed here.
322   // That code could be slightly simplified by not doing that, though maybe
323   // it is simpler conceptually to keep the code above in "register mode"
324   // until this transition point.
325   // FIXME: we are not processing inline assembly, which contains register
326   // operands, because it is used by later target generic code.
327   if (MI->isDebugInstr() || MI->isLabel() || MI->isInlineAsm())
328     return;
329 
330   // Transform to _S instruction.
331   auto RegOpcode = OutMI.getOpcode();
332   auto StackOpcode = WebAssembly::getStackOpcode(RegOpcode);
333   assert(StackOpcode != -1 && "Failed to stackify instruction");
334   OutMI.setOpcode(StackOpcode);
335 
336   // Remove register operands.
337   for (auto I = OutMI.getNumOperands(); I; --I) {
338     auto &MO = OutMI.getOperand(I - 1);
339     if (MO.isReg()) {
340       OutMI.erase(&MO);
341     }
342   }
343 }
344