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