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