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 "WebAssemblyAsmPrinter.h"
17 #include "WebAssemblyMachineFunctionInfo.h"
18 #include "WebAssemblyRuntimeLibcallSignatures.h"
19 #include "WebAssemblyUtilities.h"
20 #include "llvm/CodeGen/AsmPrinter.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCExpr.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCSymbolWasm.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 using namespace llvm;
31 
32 // Defines llvm::WebAssembly::getStackOpcode to convert register instructions to
33 // stack instructions
34 #define GET_INSTRMAP_INFO 1
35 #include "WebAssemblyGenInstrInfo.inc"
36 
37 // This disables the removal of registers when lowering into MC, as required
38 // by some current tests.
39 cl::opt<bool>
40     WasmKeepRegisters("wasm-keep-registers", cl::Hidden,
41                       cl::desc("WebAssembly: output stack registers in"
42                                " instruction output for test purposes only."),
43                       cl::init(false));
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   auto *WasmSym = cast<MCSymbolWasm>(Printer.getSymbol(Global));
51 
52   if (const auto *FuncTy = dyn_cast<FunctionType>(Global->getValueType())) {
53     const MachineFunction &MF = *MO.getParent()->getParent()->getParent();
54     const TargetMachine &TM = MF.getTarget();
55     const Function &CurrentFunc = MF.getFunction();
56 
57     SmallVector<MVT, 1> ResultMVTs;
58     SmallVector<MVT, 4> ParamMVTs;
59     computeSignatureVTs(FuncTy, CurrentFunc, TM, ParamMVTs, ResultMVTs);
60 
61     auto Signature = signatureFromMVTs(ResultMVTs, ParamMVTs);
62     WasmSym->setSignature(Signature.get());
63     Printer.addSignature(std::move(Signature));
64     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
65   }
66 
67   return WasmSym;
68 }
69 
70 MCSymbol *WebAssemblyMCInstLower::GetExternalSymbolSymbol(
71     const MachineOperand &MO) const {
72   const char *Name = MO.getSymbolName();
73   auto *WasmSym = cast<MCSymbolWasm>(Printer.GetExternalSymbolSymbol(Name));
74   const WebAssemblySubtarget &Subtarget = Printer.getSubtarget();
75 
76   // Except for the two exceptions (__stack_pointer and __cpp_exception), all
77   // other external symbols used by CodeGen are functions. It's OK to hardcode
78   // knowledge of specific symbols here; this method is precisely there for
79   // fetching the signatures of known Clang-provided symbols.
80   if (strcmp(Name, "__stack_pointer") == 0) {
81     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
82     WasmSym->setGlobalType(wasm::WasmGlobalType{
83         uint8_t(Subtarget.hasAddr64() ? wasm::WASM_TYPE_I64
84                                       : wasm::WASM_TYPE_I32),
85         true});
86     return WasmSym;
87   }
88 
89   SmallVector<wasm::ValType, 4> Returns;
90   SmallVector<wasm::ValType, 4> Params;
91   if (strcmp(Name, "__cpp_exception") == 0) {
92     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_EVENT);
93     // We can't confirm its signature index for now because there can be
94     // imported exceptions. Set it to be 0 for now.
95     WasmSym->setEventType(
96         {wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION, /* SigIndex */ 0});
97     // We may have multiple C++ compilation units to be linked together, each of
98     // which defines the exception symbol. To resolve them, we declare them as
99     // weak.
100     WasmSym->setWeak(true);
101     WasmSym->setExternal(true);
102 
103     // All C++ exceptions are assumed to have a single i32 (for wasm32) or i64
104     // (for wasm64) param type and void return type. The reaon is, all C++
105     // exception values are pointers, and to share the type section with
106     // functions, exceptions are assumed to have void return type.
107     Params.push_back(Subtarget.hasAddr64() ? wasm::ValType::I64
108                                            : wasm::ValType::I32);
109   } else { // Function symbols
110     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
111     getLibcallSignature(Subtarget, Name, Returns, Params);
112   }
113   auto Signature =
114       make_unique<wasm::WasmSignature>(std::move(Returns), std::move(Params));
115   WasmSym->setSignature(Signature.get());
116   Printer.addSignature(std::move(Signature));
117 
118   return WasmSym;
119 }
120 
121 MCOperand WebAssemblyMCInstLower::lowerSymbolOperand(MCSymbol *Sym,
122                                                      int64_t Offset,
123                                                      bool IsFunc, bool IsGlob,
124                                                      bool IsEvent) const {
125   MCSymbolRefExpr::VariantKind VK =
126       IsFunc ? MCSymbolRefExpr::VK_WebAssembly_FUNCTION
127              : IsGlob ? MCSymbolRefExpr::VK_WebAssembly_GLOBAL
128                       : IsEvent ? MCSymbolRefExpr::VK_WebAssembly_EVENT
129                                 : MCSymbolRefExpr::VK_None;
130 
131   const MCExpr *Expr = MCSymbolRefExpr::create(Sym, VK, Ctx);
132 
133   if (Offset != 0) {
134     if (IsFunc)
135       report_fatal_error("Function addresses with offsets not supported");
136     if (IsGlob)
137       report_fatal_error("Global indexes with offsets not supported");
138     if (IsEvent)
139       report_fatal_error("Event indexes with offsets not supported");
140     Expr =
141         MCBinaryExpr::createAdd(Expr, MCConstantExpr::create(Offset, Ctx), Ctx);
142   }
143 
144   return MCOperand::createExpr(Expr);
145 }
146 
147 // Return the WebAssembly type associated with the given register class.
148 static wasm::ValType getType(const TargetRegisterClass *RC) {
149   if (RC == &WebAssembly::I32RegClass)
150     return wasm::ValType::I32;
151   if (RC == &WebAssembly::I64RegClass)
152     return wasm::ValType::I64;
153   if (RC == &WebAssembly::F32RegClass)
154     return wasm::ValType::F32;
155   if (RC == &WebAssembly::F64RegClass)
156     return wasm::ValType::F64;
157   if (RC == &WebAssembly::V128RegClass)
158     return wasm::ValType::V128;
159   llvm_unreachable("Unexpected register class");
160 }
161 
162 void WebAssemblyMCInstLower::lower(const MachineInstr *MI,
163                                    MCInst &OutMI) const {
164   OutMI.setOpcode(MI->getOpcode());
165 
166   const MCInstrDesc &Desc = MI->getDesc();
167   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
168     const MachineOperand &MO = MI->getOperand(I);
169 
170     MCOperand MCOp;
171     switch (MO.getType()) {
172     default:
173       MI->print(errs());
174       llvm_unreachable("unknown operand type");
175     case MachineOperand::MO_MachineBasicBlock:
176       MI->print(errs());
177       llvm_unreachable("MachineBasicBlock operand should have been rewritten");
178     case MachineOperand::MO_Register: {
179       // Ignore all implicit register operands.
180       if (MO.isImplicit())
181         continue;
182       const WebAssemblyFunctionInfo &MFI =
183           *MI->getParent()->getParent()->getInfo<WebAssemblyFunctionInfo>();
184       unsigned WAReg = MFI.getWAReg(MO.getReg());
185       MCOp = MCOperand::createReg(WAReg);
186       break;
187     }
188     case MachineOperand::MO_Immediate:
189       if (I < Desc.NumOperands) {
190         const MCOperandInfo &Info = Desc.OpInfo[I];
191         if (Info.OperandType == WebAssembly::OPERAND_TYPEINDEX) {
192           MCSymbol *Sym = Printer.createTempSymbol("typeindex");
193 
194           SmallVector<wasm::ValType, 4> Returns;
195           SmallVector<wasm::ValType, 4> Params;
196 
197           const MachineRegisterInfo &MRI =
198               MI->getParent()->getParent()->getRegInfo();
199           for (const MachineOperand &MO : MI->defs())
200             Returns.push_back(getType(MRI.getRegClass(MO.getReg())));
201           for (const MachineOperand &MO : MI->explicit_uses())
202             if (MO.isReg())
203               Params.push_back(getType(MRI.getRegClass(MO.getReg())));
204 
205           // call_indirect instructions have a callee operand at the end which
206           // doesn't count as a param.
207           if (WebAssembly::isCallIndirect(*MI))
208             Params.pop_back();
209 
210           auto *WasmSym = cast<MCSymbolWasm>(Sym);
211           auto Signature = make_unique<wasm::WasmSignature>(std::move(Returns),
212                                                             std::move(Params));
213           WasmSym->setSignature(Signature.get());
214           Printer.addSignature(std::move(Signature));
215           WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
216 
217           const MCExpr *Expr = MCSymbolRefExpr::create(
218               WasmSym, MCSymbolRefExpr::VK_WebAssembly_TYPEINDEX, Ctx);
219           MCOp = MCOperand::createExpr(Expr);
220           break;
221         }
222       }
223       MCOp = MCOperand::createImm(MO.getImm());
224       break;
225     case MachineOperand::MO_FPImmediate: {
226       // TODO: MC converts all floating point immediate operands to double.
227       // This is fine for numeric values, but may cause NaNs to change bits.
228       const ConstantFP *Imm = MO.getFPImm();
229       if (Imm->getType()->isFloatTy())
230         MCOp = MCOperand::createFPImm(Imm->getValueAPF().convertToFloat());
231       else if (Imm->getType()->isDoubleTy())
232         MCOp = MCOperand::createFPImm(Imm->getValueAPF().convertToDouble());
233       else
234         llvm_unreachable("unknown floating point immediate type");
235       break;
236     }
237     case MachineOperand::MO_GlobalAddress:
238       assert(MO.getTargetFlags() == WebAssemblyII::MO_NO_FLAG &&
239              "WebAssembly does not use target flags on GlobalAddresses");
240       MCOp = lowerSymbolOperand(GetGlobalAddressSymbol(MO), MO.getOffset(),
241                                 MO.getGlobal()->getValueType()->isFunctionTy(),
242                                 false, false);
243       break;
244     case MachineOperand::MO_ExternalSymbol:
245       // The target flag indicates whether this is a symbol for a
246       // variable or a function.
247       assert((MO.getTargetFlags() & ~WebAssemblyII::MO_SYMBOL_MASK) == 0 &&
248              "WebAssembly uses only symbol flags on ExternalSymbols");
249       MCOp = lowerSymbolOperand(
250           GetExternalSymbolSymbol(MO), /*Offset=*/0,
251           (MO.getTargetFlags() & WebAssemblyII::MO_SYMBOL_FUNCTION) != 0,
252           (MO.getTargetFlags() & WebAssemblyII::MO_SYMBOL_GLOBAL) != 0,
253           (MO.getTargetFlags() & WebAssemblyII::MO_SYMBOL_EVENT) != 0);
254       break;
255     case MachineOperand::MO_MCSymbol:
256       // This is currently used only for LSDA symbols (GCC_except_table),
257       // because global addresses or other external symbols are handled above.
258       assert(MO.getTargetFlags() == 0 &&
259              "WebAssembly does not use target flags on MCSymbol");
260       MCOp = lowerSymbolOperand(MO.getMCSymbol(), /*Offset=*/0, false, false,
261                                 false);
262       break;
263     }
264 
265     OutMI.addOperand(MCOp);
266   }
267 
268   if (!WasmKeepRegisters)
269     removeRegisterOperands(MI, OutMI);
270 }
271 
272 static void removeRegisterOperands(const MachineInstr *MI, MCInst &OutMI) {
273   // Remove all uses of stackified registers to bring the instruction format
274   // into its final stack form used thruout MC, and transition opcodes to
275   // their _S variant.
276   // We do this seperate from the above code that still may need these
277   // registers for e.g. call_indirect signatures.
278   // See comments in lib/Target/WebAssembly/WebAssemblyInstrFormats.td for
279   // details.
280   // TODO: the code above creates new registers which are then removed here.
281   // That code could be slightly simplified by not doing that, though maybe
282   // it is simpler conceptually to keep the code above in "register mode"
283   // until this transition point.
284   // FIXME: we are not processing inline assembly, which contains register
285   // operands, because it is used by later target generic code.
286   if (MI->isDebugInstr() || MI->isLabel() || MI->isInlineAsm())
287     return;
288 
289   // Transform to _S instruction.
290   auto RegOpcode = OutMI.getOpcode();
291   auto StackOpcode = WebAssembly::getStackOpcode(RegOpcode);
292   assert(StackOpcode != -1 && "Failed to stackify instruction");
293   OutMI.setOpcode(StackOpcode);
294 
295   // Remove register operands.
296   for (auto I = OutMI.getNumOperands(); I; --I) {
297     auto &MO = OutMI.getOperand(I - 1);
298     if (MO.isReg()) {
299       OutMI.erase(&MO);
300     }
301   }
302 }
303