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 /// \brief 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/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/MC/MCSymbolWasm.h"
37 #include "llvm/MC/MCSymbolELF.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::v4f32})
54     if (TRI->isTypeLegalForClass(*TRC, T))
55       return T;
56   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 (const auto &F : M) {
82     // Emit function type info for all undefined functions
83     if (F.isDeclarationForLinker() && !F.isIntrinsic()) {
84       SmallVector<MVT, 4> Results;
85       SmallVector<MVT, 4> Params;
86       ComputeSignatureVTs(F, TM, Params, Results);
87       MCSymbol *Sym = getSymbol(&F);
88       getTargetStreamer()->emitIndirectFunctionType(Sym, Params, Results);
89 
90       if (TM.getTargetTriple().isOSBinFormatWasm() &&
91           F.hasFnAttribute("wasm-import-module")) {
92         MCSymbolWasm *WasmSym = cast<MCSymbolWasm>(Sym);
93         StringRef Name = F.getFnAttribute("wasm-import-module")
94                              .getValueAsString();
95         getTargetStreamer()->emitImportModule(WasmSym, Name);
96       }
97     }
98   }
99   for (const auto &G : M.globals()) {
100     if (!G.hasInitializer() && G.hasExternalLinkage()) {
101       if (G.getValueType()->isSized()) {
102         uint16_t Size = M.getDataLayout().getTypeAllocSize(G.getValueType());
103         if (TM.getTargetTriple().isOSBinFormatELF())
104           getTargetStreamer()->emitGlobalImport(G.getGlobalIdentifier());
105         OutStreamer->emitELFSize(getSymbol(&G),
106                                  MCConstantExpr::create(Size, OutContext));
107       }
108     }
109   }
110 }
111 
112 void WebAssemblyAsmPrinter::EmitConstantPool() {
113   assert(MF->getConstantPool()->getConstants().empty() &&
114          "WebAssembly disables constant pools");
115 }
116 
117 void WebAssemblyAsmPrinter::EmitJumpTableInfo() {
118   // Nothing to do; jump tables are incorporated into the instruction stream.
119 }
120 
121 void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
122   getTargetStreamer()->emitParam(CurrentFnSym, MFI->getParams());
123 
124   SmallVector<MVT, 4> ResultVTs;
125   const Function &F = MF->getFunction();
126 
127   // Emit the function index.
128   if (MDNode *Idx = F.getMetadata("wasm.index")) {
129     assert(Idx->getNumOperands() == 1);
130 
131     getTargetStreamer()->emitIndIdx(AsmPrinter::lowerConstant(
132         cast<ConstantAsMetadata>(Idx->getOperand(0))->getValue()));
133   }
134 
135   ComputeLegalValueVTs(F, TM, F.getReturnType(), ResultVTs);
136 
137   // If the return type needs to be legalized it will get converted into
138   // passing a pointer.
139   if (ResultVTs.size() == 1)
140     getTargetStreamer()->emitResult(CurrentFnSym, ResultVTs);
141   else
142     getTargetStreamer()->emitResult(CurrentFnSym, ArrayRef<MVT>());
143 
144   if (TM.getTargetTriple().isOSBinFormatELF()) {
145     assert(MFI->getLocals().empty());
146     for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
147       unsigned VReg = TargetRegisterInfo::index2VirtReg(Idx);
148       unsigned WAReg = MFI->getWAReg(VReg);
149       // Don't declare unused registers.
150       if (WAReg == WebAssemblyFunctionInfo::UnusedReg)
151         continue;
152       // Don't redeclare parameters.
153       if (WAReg < MFI->getParams().size())
154         continue;
155       // Don't declare stackified registers.
156       if (int(WAReg) < 0)
157         continue;
158       MFI->addLocal(getRegType(VReg));
159     }
160   }
161 
162   getTargetStreamer()->emitLocal(MFI->getLocals());
163 
164   AsmPrinter::EmitFunctionBodyStart();
165 }
166 
167 void WebAssemblyAsmPrinter::EmitFunctionBodyEnd() {
168   if (TM.getTargetTriple().isOSBinFormatELF())
169     getTargetStreamer()->emitEndFunc();
170 }
171 
172 void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
173   DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
174 
175   switch (MI->getOpcode()) {
176   case WebAssembly::ARGUMENT_I32:
177   case WebAssembly::ARGUMENT_I64:
178   case WebAssembly::ARGUMENT_F32:
179   case WebAssembly::ARGUMENT_F64:
180   case WebAssembly::ARGUMENT_v16i8:
181   case WebAssembly::ARGUMENT_v8i16:
182   case WebAssembly::ARGUMENT_v4i32:
183   case WebAssembly::ARGUMENT_v4f32:
184     // These represent values which are live into the function entry, so there's
185     // no instruction to emit.
186     break;
187   case WebAssembly::FALLTHROUGH_RETURN_I32:
188   case WebAssembly::FALLTHROUGH_RETURN_I64:
189   case WebAssembly::FALLTHROUGH_RETURN_F32:
190   case WebAssembly::FALLTHROUGH_RETURN_F64:
191   case WebAssembly::FALLTHROUGH_RETURN_v16i8:
192   case WebAssembly::FALLTHROUGH_RETURN_v8i16:
193   case WebAssembly::FALLTHROUGH_RETURN_v4i32:
194   case WebAssembly::FALLTHROUGH_RETURN_v4f32: {
195     // These instructions represent the implicit return at the end of a
196     // function body. The operand is always a pop.
197     assert(MFI->isVRegStackified(MI->getOperand(0).getReg()));
198 
199     if (isVerbose()) {
200       OutStreamer->AddComment("fallthrough-return: $pop" +
201                               Twine(MFI->getWARegStackId(
202                                   MFI->getWAReg(MI->getOperand(0).getReg()))));
203       OutStreamer->AddBlankLine();
204     }
205     break;
206   }
207   case WebAssembly::FALLTHROUGH_RETURN_VOID:
208     // This instruction represents the implicit return at the end of a
209     // function body with no return value.
210     if (isVerbose()) {
211       OutStreamer->AddComment("fallthrough-return");
212       OutStreamer->AddBlankLine();
213     }
214     break;
215   default: {
216     WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
217     MCInst TmpInst;
218     MCInstLowering.Lower(MI, TmpInst);
219     EmitToStreamer(*OutStreamer, TmpInst);
220     break;
221   }
222   }
223 }
224 
225 const MCExpr *WebAssemblyAsmPrinter::lowerConstant(const Constant *CV) {
226   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
227     if (GV->getValueType()->isFunctionTy()) {
228       return MCSymbolRefExpr::create(
229           getSymbol(GV), MCSymbolRefExpr::VK_WebAssembly_FUNCTION, OutContext);
230     }
231   return AsmPrinter::lowerConstant(CV);
232 }
233 
234 bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
235                                             unsigned OpNo, unsigned AsmVariant,
236                                             const char *ExtraCode,
237                                             raw_ostream &OS) {
238   if (AsmVariant != 0)
239     report_fatal_error("There are no defined alternate asm variants");
240 
241   // First try the generic code, which knows about modifiers like 'c' and 'n'.
242   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, OS))
243     return false;
244 
245   if (!ExtraCode) {
246     const MachineOperand &MO = MI->getOperand(OpNo);
247     switch (MO.getType()) {
248     case MachineOperand::MO_Immediate:
249       OS << MO.getImm();
250       return false;
251     case MachineOperand::MO_Register:
252       OS << regToString(MO);
253       return false;
254     case MachineOperand::MO_GlobalAddress:
255       getSymbol(MO.getGlobal())->print(OS, MAI);
256       printOffset(MO.getOffset(), OS);
257       return false;
258     case MachineOperand::MO_ExternalSymbol:
259       GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI);
260       printOffset(MO.getOffset(), OS);
261       return false;
262     case MachineOperand::MO_MachineBasicBlock:
263       MO.getMBB()->getSymbol()->print(OS, MAI);
264       return false;
265     default:
266       break;
267     }
268   }
269 
270   return true;
271 }
272 
273 bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
274                                                   unsigned OpNo,
275                                                   unsigned AsmVariant,
276                                                   const char *ExtraCode,
277                                                   raw_ostream &OS) {
278   if (AsmVariant != 0)
279     report_fatal_error("There are no defined alternate asm variants");
280 
281   // The current approach to inline asm is that "r" constraints are expressed
282   // as local indices, rather than values on the operand stack. This simplifies
283   // using "r" as it eliminates the need to push and pop the values in a
284   // particular order, however it also makes it impossible to have an "m"
285   // constraint. So we don't support it.
286 
287   return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, AsmVariant, ExtraCode, OS);
288 }
289 
290 // Force static initialization.
291 extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
292   RegisterAsmPrinter<WebAssemblyAsmPrinter> X(getTheWebAssemblyTarget32());
293   RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(getTheWebAssemblyTarget64());
294 }
295