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 "WebAssembly.h"
18 #include "InstPrinter/WebAssemblyInstPrinter.h"
19 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
20 #include "MCTargetDesc/WebAssemblyTargetStreamer.h"
21 #include "WebAssemblyMCInstLower.h"
22 #include "WebAssemblyMachineFunctionInfo.h"
23 #include "WebAssemblyRegisterInfo.h"
24 #include "WebAssemblySubtarget.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/IR/DataLayout.h"
31 #include "llvm/MC/MCContext.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Support/raw_ostream.h"
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "asm-printer"
40 
41 namespace {
42 
43 class WebAssemblyAsmPrinter final : public AsmPrinter {
44   const MachineRegisterInfo *MRI;
45   const WebAssemblyFunctionInfo *MFI;
46 
47 public:
48   WebAssemblyAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
49       : AsmPrinter(TM, std::move(Streamer)), MRI(nullptr), MFI(nullptr) {}
50 
51 private:
52   const char *getPassName() const override {
53     return "WebAssembly Assembly Printer";
54   }
55 
56   //===------------------------------------------------------------------===//
57   // MachineFunctionPass Implementation.
58   //===------------------------------------------------------------------===//
59 
60   bool runOnMachineFunction(MachineFunction &MF) override {
61     MRI = &MF.getRegInfo();
62     MFI = MF.getInfo<WebAssemblyFunctionInfo>();
63     return AsmPrinter::runOnMachineFunction(MF);
64   }
65 
66   //===------------------------------------------------------------------===//
67   // AsmPrinter Implementation.
68   //===------------------------------------------------------------------===//
69 
70   void EmitEndOfAsmFile(Module &M) override;
71   void EmitJumpTableInfo() override;
72   void EmitConstantPool() override;
73   void EmitFunctionBodyStart() override;
74   void EmitFunctionBodyEnd() override;
75   void EmitInstruction(const MachineInstr *MI) override;
76   const MCExpr *lowerConstant(const Constant *CV) override;
77   bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
78                        unsigned AsmVariant, const char *ExtraCode,
79                        raw_ostream &OS) override;
80   bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
81                              unsigned AsmVariant, const char *ExtraCode,
82                              raw_ostream &OS) override;
83 
84   MVT getRegType(unsigned RegNo) const;
85   const char *toString(MVT VT) const;
86   std::string regToString(const MachineOperand &MO);
87   WebAssemblyTargetStreamer *getTargetStreamer();
88 };
89 
90 } // end anonymous namespace
91 
92 //===----------------------------------------------------------------------===//
93 // Helpers.
94 //===----------------------------------------------------------------------===//
95 
96 MVT WebAssemblyAsmPrinter::getRegType(unsigned RegNo) const {
97   const TargetRegisterClass *TRC = MRI->getRegClass(RegNo);
98   for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
99     if (TRC->hasType(T))
100       return T;
101   DEBUG(errs() << "Unknown type for register number: " << RegNo);
102   llvm_unreachable("Unknown register type");
103   return MVT::Other;
104 }
105 
106 const char *WebAssemblyAsmPrinter::toString(MVT VT) const {
107   return WebAssembly::TypeToString(VT);
108 }
109 
110 std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
111   unsigned RegNo = MO.getReg();
112   assert(TargetRegisterInfo::isVirtualRegister(RegNo) &&
113          "Unlowered physical register encountered during assembly printing");
114   assert(!MFI->isVRegStackified(RegNo));
115   unsigned WAReg = MFI->getWAReg(RegNo);
116   assert(WAReg != WebAssemblyFunctionInfo::UnusedReg);
117   return '$' + utostr(WAReg);
118 }
119 
120 WebAssemblyTargetStreamer *WebAssemblyAsmPrinter::getTargetStreamer() {
121   MCTargetStreamer *TS = OutStreamer->getTargetStreamer();
122   return static_cast<WebAssemblyTargetStreamer *>(TS);
123 }
124 
125 //===----------------------------------------------------------------------===//
126 // WebAssemblyAsmPrinter Implementation.
127 //===----------------------------------------------------------------------===//
128 static void ComputeLegalValueVTs(const Function &F, const TargetMachine &TM,
129                                  Type *Ty, SmallVectorImpl<MVT> &ValueVTs) {
130   const DataLayout &DL(F.getParent()->getDataLayout());
131   const WebAssemblyTargetLowering &TLI =
132       *TM.getSubtarget<WebAssemblySubtarget>(F).getTargetLowering();
133   SmallVector<EVT, 4> VTs;
134   ComputeValueVTs(TLI, DL, Ty, VTs);
135 
136   for (EVT VT : VTs) {
137     unsigned NumRegs = TLI.getNumRegisters(F.getContext(), VT);
138     MVT RegisterVT = TLI.getRegisterType(F.getContext(), VT);
139     for (unsigned i = 0; i != NumRegs; ++i)
140       ValueVTs.push_back(RegisterVT);
141   }
142 }
143 
144 void WebAssemblyAsmPrinter::EmitEndOfAsmFile(Module &M) {
145   for (const auto &F : M) {
146     // Emit function type info for all undefined functions
147     if (F.isDeclarationForLinker() && !F.isIntrinsic()) {
148       SmallVector<MVT, 4> SignatureVTs;
149       ComputeLegalValueVTs(F, TM, F.getReturnType(), SignatureVTs);
150       size_t NumResults = SignatureVTs.size();
151       if (SignatureVTs.size() > 1) {
152         // WebAssembly currently can't lower returns of multiple values without
153         // demoting to sret (see WebAssemblyTargetLowering::CanLowerReturn). So
154         // replace multiple return values with a pointer parameter.
155         SignatureVTs.clear();
156         SignatureVTs.push_back(
157             MVT::getIntegerVT(M.getDataLayout().getPointerSizeInBits()));
158         NumResults = 0;
159       }
160 
161       for (auto &Arg : F.args()) {
162         ComputeLegalValueVTs(F, TM, Arg.getType(), SignatureVTs);
163       }
164 
165       getTargetStreamer()->emitIndirectFunctionType(F.getName(), SignatureVTs,
166                                                     NumResults);
167     }
168   }
169 }
170 
171 void WebAssemblyAsmPrinter::EmitConstantPool() {
172   assert(MF->getConstantPool()->getConstants().empty() &&
173          "WebAssembly disables constant pools");
174 }
175 
176 void WebAssemblyAsmPrinter::EmitJumpTableInfo() {
177   // Nothing to do; jump tables are incorporated into the instruction stream.
178 }
179 
180 void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
181   if (!MFI->getParams().empty())
182     getTargetStreamer()->emitParam(MFI->getParams());
183 
184   SmallVector<MVT, 4> ResultVTs;
185   const Function &F(*MF->getFunction());
186   ComputeLegalValueVTs(F, TM, F.getReturnType(), ResultVTs);
187 
188   // If the return type needs to be legalized it will get converted into
189   // passing a pointer.
190   if (ResultVTs.size() == 1)
191     getTargetStreamer()->emitResult(ResultVTs);
192 
193   bool AnyWARegs = false;
194   SmallVector<MVT, 16> LocalTypes;
195   for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
196     unsigned VReg = TargetRegisterInfo::index2VirtReg(Idx);
197     unsigned WAReg = MFI->getWAReg(VReg);
198     // Don't declare unused registers.
199     if (WAReg == WebAssemblyFunctionInfo::UnusedReg)
200       continue;
201     // Don't redeclare parameters.
202     if (WAReg < MFI->getParams().size())
203       continue;
204     // Don't declare stackified registers.
205     if (int(WAReg) < 0)
206       continue;
207     LocalTypes.push_back(getRegType(VReg));
208     AnyWARegs = true;
209   }
210   if (AnyWARegs)
211     getTargetStreamer()->emitLocal(LocalTypes);
212 
213   AsmPrinter::EmitFunctionBodyStart();
214 }
215 
216 void WebAssemblyAsmPrinter::EmitFunctionBodyEnd() {
217   getTargetStreamer()->emitEndFunc();
218 }
219 
220 void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
221   DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
222 
223   switch (MI->getOpcode()) {
224   case WebAssembly::ARGUMENT_I32:
225   case WebAssembly::ARGUMENT_I64:
226   case WebAssembly::ARGUMENT_F32:
227   case WebAssembly::ARGUMENT_F64:
228     // These represent values which are live into the function entry, so there's
229     // no instruction to emit.
230     break;
231   case WebAssembly::FALLTHROUGH_RETURN_I32:
232   case WebAssembly::FALLTHROUGH_RETURN_I64:
233   case WebAssembly::FALLTHROUGH_RETURN_F32:
234   case WebAssembly::FALLTHROUGH_RETURN_F64: {
235     // These instructions represent the implicit return at the end of a
236     // function body. The operand is always a pop.
237     assert(MFI->isVRegStackified(MI->getOperand(0).getReg()));
238 
239     if (isVerbose()) {
240       OutStreamer->AddComment("fallthrough-return: $pop" +
241                               utostr(MFI->getWARegStackId(
242                                   MFI->getWAReg(MI->getOperand(0).getReg()))));
243       OutStreamer->AddBlankLine();
244     }
245     break;
246   }
247   case WebAssembly::FALLTHROUGH_RETURN_VOID:
248     // This instruction represents the implicit return at the end of a
249     // function body with no return value.
250     if (isVerbose()) {
251       OutStreamer->AddComment("fallthrough-return");
252       OutStreamer->AddBlankLine();
253     }
254     break;
255   default: {
256     WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
257     MCInst TmpInst;
258     MCInstLowering.Lower(MI, TmpInst);
259     EmitToStreamer(*OutStreamer, TmpInst);
260     break;
261   }
262   }
263 }
264 
265 const MCExpr *WebAssemblyAsmPrinter::lowerConstant(const Constant *CV) {
266   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
267     if (GV->getValueType()->isFunctionTy())
268       return MCSymbolRefExpr::create(
269           getSymbol(GV), MCSymbolRefExpr::VK_WebAssembly_FUNCTION, OutContext);
270   return AsmPrinter::lowerConstant(CV);
271 }
272 
273 bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
274                                             unsigned OpNo, unsigned AsmVariant,
275                                             const char *ExtraCode,
276                                             raw_ostream &OS) {
277   if (AsmVariant != 0)
278     report_fatal_error("There are no defined alternate asm variants");
279 
280   // First try the generic code, which knows about modifiers like 'c' and 'n'.
281   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, OS))
282     return false;
283 
284   if (!ExtraCode) {
285     const MachineOperand &MO = MI->getOperand(OpNo);
286     switch (MO.getType()) {
287     case MachineOperand::MO_Immediate:
288       OS << MO.getImm();
289       return false;
290     case MachineOperand::MO_Register:
291       OS << regToString(MO);
292       return false;
293     case MachineOperand::MO_GlobalAddress:
294       getSymbol(MO.getGlobal())->print(OS, MAI);
295       printOffset(MO.getOffset(), OS);
296       return false;
297     case MachineOperand::MO_ExternalSymbol:
298       GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI);
299       printOffset(MO.getOffset(), OS);
300       return false;
301     case MachineOperand::MO_MachineBasicBlock:
302       MO.getMBB()->getSymbol()->print(OS, MAI);
303       return false;
304     default:
305       break;
306     }
307   }
308 
309   return true;
310 }
311 
312 bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
313                                                   unsigned OpNo,
314                                                   unsigned AsmVariant,
315                                                   const char *ExtraCode,
316                                                   raw_ostream &OS) {
317   if (AsmVariant != 0)
318     report_fatal_error("There are no defined alternate asm variants");
319 
320   if (!ExtraCode) {
321     // TODO: For now, we just hard-code 0 as the constant offset; teach
322     // SelectInlineAsmMemoryOperand how to do address mode matching.
323     OS << "0(" + regToString(MI->getOperand(OpNo)) + ')';
324     return false;
325   }
326 
327   return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, AsmVariant, ExtraCode, OS);
328 }
329 
330 // Force static initialization.
331 extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
332   RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32);
333   RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64);
334 }
335