1 //===-- WebAssemblyAsmPrinter.cpp - WebAssembly LLVM assembly writer ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// This file contains a printer that converts from our internal
12 /// representation of machine-dependent LLVM code to the WebAssembly assembly
13 /// language.
14 ///
15 //===----------------------------------------------------------------------===//
16 
17 #include "WebAssemblyAsmPrinter.h"
18 #include "InstPrinter/WebAssemblyInstPrinter.h"
19 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
20 #include "MCTargetDesc/WebAssemblyTargetStreamer.h"
21 #include "WebAssembly.h"
22 #include "WebAssemblyMCInstLower.h"
23 #include "WebAssemblyMachineFunctionInfo.h"
24 #include "WebAssemblyRegisterInfo.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/Analysis.h"
27 #include "llvm/CodeGen/AsmPrinter.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/MC/MCContext.h"
34 #include "llvm/MC/MCSectionWasm.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/MC/MCSymbolWasm.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/raw_ostream.h"
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "asm-printer"
44 
45 //===----------------------------------------------------------------------===//
46 // Helpers.
47 //===----------------------------------------------------------------------===//
48 
49 MVT WebAssemblyAsmPrinter::getRegType(unsigned RegNo) const {
50   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
51   const TargetRegisterClass *TRC = MRI->getRegClass(RegNo);
52   for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64, MVT::v16i8, MVT::v8i16,
53                 MVT::v4i32, MVT::v2i64, MVT::v4f32, MVT::v2f64})
54     if (TRI->isTypeLegalForClass(*TRC, T))
55       return T;
56   LLVM_DEBUG(errs() << "Unknown type for register number: " << RegNo);
57   llvm_unreachable("Unknown register type");
58   return MVT::Other;
59 }
60 
61 std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
62   unsigned RegNo = MO.getReg();
63   assert(TargetRegisterInfo::isVirtualRegister(RegNo) &&
64          "Unlowered physical register encountered during assembly printing");
65   assert(!MFI->isVRegStackified(RegNo));
66   unsigned WAReg = MFI->getWAReg(RegNo);
67   assert(WAReg != WebAssemblyFunctionInfo::UnusedReg);
68   return '$' + utostr(WAReg);
69 }
70 
71 WebAssemblyTargetStreamer *WebAssemblyAsmPrinter::getTargetStreamer() {
72   MCTargetStreamer *TS = OutStreamer->getTargetStreamer();
73   return static_cast<WebAssemblyTargetStreamer *>(TS);
74 }
75 
76 //===----------------------------------------------------------------------===//
77 // WebAssemblyAsmPrinter Implementation.
78 //===----------------------------------------------------------------------===//
79 
80 void WebAssemblyAsmPrinter::EmitEndOfAsmFile(Module &M) {
81   for (auto &It : OutContext.getSymbols()) {
82     // Emit a .globaltype and .eventtype declaration.
83     auto Sym = cast<MCSymbolWasm>(It.getValue());
84     if (Sym->getType() == wasm::WASM_SYMBOL_TYPE_GLOBAL)
85       getTargetStreamer()->emitGlobalType(Sym);
86     else if (Sym->getType() == wasm::WASM_SYMBOL_TYPE_EVENT)
87       getTargetStreamer()->emitEventType(Sym);
88   }
89 
90   for (const auto &F : M) {
91     // Emit function type info for all undefined functions
92     if (F.isDeclarationForLinker() && !F.isIntrinsic()) {
93       SmallVector<MVT, 4> Results;
94       SmallVector<MVT, 4> Params;
95       ComputeSignatureVTs(F.getFunctionType(), F, TM, Params, Results);
96       auto *Sym = cast<MCSymbolWasm>(getSymbol(&F));
97       Sym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
98       if (!Sym->getSignature()) {
99         auto Signature = SignatureFromMVTs(Results, Params);
100         Sym->setSignature(Signature.get());
101         addSignature(std::move(Signature));
102       }
103       // FIXME: this was originally intended for post-linking and was only used
104       // for imports that were only called indirectly (i.e. s2wasm could not
105       // infer the type from a call). With object files it applies to all
106       // imports. so fix the names and the tests, or rethink how import
107       // delcarations work in asm files.
108       getTargetStreamer()->emitFunctionType(Sym);
109 
110       if (TM.getTargetTriple().isOSBinFormatWasm() &&
111           F.hasFnAttribute("wasm-import-module")) {
112         StringRef Name =
113             F.getFnAttribute("wasm-import-module").getValueAsString();
114         Sym->setModuleName(Name);
115         getTargetStreamer()->emitImportModule(Sym, Name);
116       }
117     }
118   }
119 
120   for (const auto &G : M.globals()) {
121     if (!G.hasInitializer() && G.hasExternalLinkage()) {
122       if (G.getValueType()->isSized()) {
123         uint16_t Size = M.getDataLayout().getTypeAllocSize(G.getValueType());
124         OutStreamer->emitELFSize(getSymbol(&G),
125                                  MCConstantExpr::create(Size, OutContext));
126       }
127     }
128   }
129 
130   if (const NamedMDNode *Named = M.getNamedMetadata("wasm.custom_sections")) {
131     for (const Metadata *MD : Named->operands()) {
132       const MDTuple *Tuple = dyn_cast<MDTuple>(MD);
133       if (!Tuple || Tuple->getNumOperands() != 2)
134         continue;
135       const MDString *Name = dyn_cast<MDString>(Tuple->getOperand(0));
136       const MDString *Contents = dyn_cast<MDString>(Tuple->getOperand(1));
137       if (!Name || !Contents)
138         continue;
139 
140       OutStreamer->PushSection();
141       std::string SectionName = (".custom_section." + Name->getString()).str();
142       MCSectionWasm *mySection =
143           OutContext.getWasmSection(SectionName, SectionKind::getMetadata());
144       OutStreamer->SwitchSection(mySection);
145       OutStreamer->EmitBytes(Contents->getString());
146       OutStreamer->PopSection();
147     }
148   }
149 }
150 
151 void WebAssemblyAsmPrinter::EmitConstantPool() {
152   assert(MF->getConstantPool()->getConstants().empty() &&
153          "WebAssembly disables constant pools");
154 }
155 
156 void WebAssemblyAsmPrinter::EmitJumpTableInfo() {
157   // Nothing to do; jump tables are incorporated into the instruction stream.
158 }
159 
160 void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
161   const Function &F = MF->getFunction();
162   SmallVector<MVT, 1> ResultVTs;
163   SmallVector<MVT, 4> ParamVTs;
164   ComputeSignatureVTs(F.getFunctionType(), F, TM, ParamVTs, ResultVTs);
165   auto Signature = SignatureFromMVTs(ResultVTs, ParamVTs);
166   auto *WasmSym = cast<MCSymbolWasm>(CurrentFnSym);
167   WasmSym->setSignature(Signature.get());
168   addSignature(std::move(Signature));
169   WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
170 
171   // FIXME: clean up how params and results are emitted (use signatures)
172   getTargetStreamer()->emitFunctionType(WasmSym);
173 
174   // Emit the function index.
175   if (MDNode *Idx = F.getMetadata("wasm.index")) {
176     assert(Idx->getNumOperands() == 1);
177 
178     getTargetStreamer()->emitIndIdx(AsmPrinter::lowerConstant(
179         cast<ConstantAsMetadata>(Idx->getOperand(0))->getValue()));
180   }
181 
182   SmallVector<wasm::ValType, 16> Locals;
183   ValTypesFromMVTs(MFI->getLocals(), Locals);
184   getTargetStreamer()->emitLocal(Locals);
185 
186   AsmPrinter::EmitFunctionBodyStart();
187 }
188 
189 void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
190   LLVM_DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
191 
192   switch (MI->getOpcode()) {
193   case WebAssembly::ARGUMENT_i32:
194   case WebAssembly::ARGUMENT_i32_S:
195   case WebAssembly::ARGUMENT_i64:
196   case WebAssembly::ARGUMENT_i64_S:
197   case WebAssembly::ARGUMENT_f32:
198   case WebAssembly::ARGUMENT_f32_S:
199   case WebAssembly::ARGUMENT_f64:
200   case WebAssembly::ARGUMENT_f64_S:
201   case WebAssembly::ARGUMENT_v16i8:
202   case WebAssembly::ARGUMENT_v16i8_S:
203   case WebAssembly::ARGUMENT_v8i16:
204   case WebAssembly::ARGUMENT_v8i16_S:
205   case WebAssembly::ARGUMENT_v4i32:
206   case WebAssembly::ARGUMENT_v4i32_S:
207   case WebAssembly::ARGUMENT_v2i64:
208   case WebAssembly::ARGUMENT_v2i64_S:
209   case WebAssembly::ARGUMENT_v4f32:
210   case WebAssembly::ARGUMENT_v4f32_S:
211   case WebAssembly::ARGUMENT_v2f64:
212   case WebAssembly::ARGUMENT_v2f64_S:
213     // These represent values which are live into the function entry, so there's
214     // no instruction to emit.
215     break;
216   case WebAssembly::FALLTHROUGH_RETURN_I32:
217   case WebAssembly::FALLTHROUGH_RETURN_I32_S:
218   case WebAssembly::FALLTHROUGH_RETURN_I64:
219   case WebAssembly::FALLTHROUGH_RETURN_I64_S:
220   case WebAssembly::FALLTHROUGH_RETURN_F32:
221   case WebAssembly::FALLTHROUGH_RETURN_F32_S:
222   case WebAssembly::FALLTHROUGH_RETURN_F64:
223   case WebAssembly::FALLTHROUGH_RETURN_F64_S:
224   case WebAssembly::FALLTHROUGH_RETURN_v16i8:
225   case WebAssembly::FALLTHROUGH_RETURN_v16i8_S:
226   case WebAssembly::FALLTHROUGH_RETURN_v8i16:
227   case WebAssembly::FALLTHROUGH_RETURN_v8i16_S:
228   case WebAssembly::FALLTHROUGH_RETURN_v4i32:
229   case WebAssembly::FALLTHROUGH_RETURN_v4i32_S:
230   case WebAssembly::FALLTHROUGH_RETURN_v2i64:
231   case WebAssembly::FALLTHROUGH_RETURN_v2i64_S:
232   case WebAssembly::FALLTHROUGH_RETURN_v4f32:
233   case WebAssembly::FALLTHROUGH_RETURN_v4f32_S:
234   case WebAssembly::FALLTHROUGH_RETURN_v2f64:
235   case WebAssembly::FALLTHROUGH_RETURN_v2f64_S: {
236     // These instructions represent the implicit return at the end of a
237     // function body. Always pops one value off the stack.
238     if (isVerbose()) {
239       OutStreamer->AddComment("fallthrough-return-value");
240       OutStreamer->AddBlankLine();
241     }
242     break;
243   }
244   case WebAssembly::FALLTHROUGH_RETURN_VOID:
245   case WebAssembly::FALLTHROUGH_RETURN_VOID_S:
246     // This instruction represents the implicit return at the end of a
247     // function body with no return value.
248     if (isVerbose()) {
249       OutStreamer->AddComment("fallthrough-return-void");
250       OutStreamer->AddBlankLine();
251     }
252     break;
253   default: {
254     WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
255     MCInst TmpInst;
256     MCInstLowering.Lower(MI, TmpInst);
257     EmitToStreamer(*OutStreamer, TmpInst);
258     break;
259   }
260   }
261 }
262 
263 const MCExpr *WebAssemblyAsmPrinter::lowerConstant(const Constant *CV) {
264   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
265     if (GV->getValueType()->isFunctionTy()) {
266       return MCSymbolRefExpr::create(
267           getSymbol(GV), MCSymbolRefExpr::VK_WebAssembly_FUNCTION, OutContext);
268     }
269   return AsmPrinter::lowerConstant(CV);
270 }
271 
272 bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
273                                             unsigned OpNo, unsigned AsmVariant,
274                                             const char *ExtraCode,
275                                             raw_ostream &OS) {
276   if (AsmVariant != 0)
277     report_fatal_error("There are no defined alternate asm variants");
278 
279   // First try the generic code, which knows about modifiers like 'c' and 'n'.
280   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, OS))
281     return false;
282 
283   if (!ExtraCode) {
284     const MachineOperand &MO = MI->getOperand(OpNo);
285     switch (MO.getType()) {
286     case MachineOperand::MO_Immediate:
287       OS << MO.getImm();
288       return false;
289     case MachineOperand::MO_Register:
290       // FIXME: only opcode that still contains registers, as required by
291       // MachineInstr::getDebugVariable().
292       assert(MI->getOpcode() == WebAssembly::INLINEASM);
293       OS << regToString(MO);
294       return false;
295     case MachineOperand::MO_GlobalAddress:
296       getSymbol(MO.getGlobal())->print(OS, MAI);
297       printOffset(MO.getOffset(), OS);
298       return false;
299     case MachineOperand::MO_ExternalSymbol:
300       GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI);
301       printOffset(MO.getOffset(), OS);
302       return false;
303     case MachineOperand::MO_MachineBasicBlock:
304       MO.getMBB()->getSymbol()->print(OS, MAI);
305       return false;
306     default:
307       break;
308     }
309   }
310 
311   return true;
312 }
313 
314 bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
315                                                   unsigned OpNo,
316                                                   unsigned AsmVariant,
317                                                   const char *ExtraCode,
318                                                   raw_ostream &OS) {
319   if (AsmVariant != 0)
320     report_fatal_error("There are no defined alternate asm variants");
321 
322   // The current approach to inline asm is that "r" constraints are expressed
323   // as local indices, rather than values on the operand stack. This simplifies
324   // using "r" as it eliminates the need to push and pop the values in a
325   // particular order, however it also makes it impossible to have an "m"
326   // constraint. So we don't support it.
327 
328   return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, AsmVariant, ExtraCode, OS);
329 }
330 
331 // Force static initialization.
332 extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
333   RegisterAsmPrinter<WebAssemblyAsmPrinter> X(getTheWebAssemblyTarget32());
334   RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(getTheWebAssemblyTarget64());
335 }
336