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 EmitJumpTableInfo() override;
71   void EmitConstantPool() override;
72   void EmitFunctionBodyStart() override;
73   void EmitFunctionBodyEnd() override;
74   void EmitInstruction(const MachineInstr *MI) override;
75   const MCExpr *lowerConstant(const Constant *CV) override;
76   bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
77                        unsigned AsmVariant, const char *ExtraCode,
78                        raw_ostream &OS) override;
79   bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
80                              unsigned AsmVariant, const char *ExtraCode,
81                              raw_ostream &OS) override;
82 
83   MVT getRegType(unsigned RegNo) const;
84   const char *toString(MVT VT) const;
85   std::string regToString(const MachineOperand &MO);
86   WebAssemblyTargetStreamer *getTargetStreamer();
87 };
88 
89 } // end anonymous namespace
90 
91 //===----------------------------------------------------------------------===//
92 // Helpers.
93 //===----------------------------------------------------------------------===//
94 
95 MVT WebAssemblyAsmPrinter::getRegType(unsigned RegNo) const {
96   const TargetRegisterClass *TRC =
97       TargetRegisterInfo::isVirtualRegister(RegNo)
98           ? MRI->getRegClass(RegNo)
99           : MRI->getTargetRegisterInfo()->getMinimalPhysRegClass(RegNo);
100   for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
101     if (TRC->hasType(T))
102       return T;
103   DEBUG(errs() << "Unknown type for register number: " << RegNo);
104   llvm_unreachable("Unknown register type");
105   return MVT::Other;
106 }
107 
108 const char *WebAssemblyAsmPrinter::toString(MVT VT) const {
109   return WebAssembly::TypeToString(VT);
110 }
111 
112 std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
113   unsigned RegNo = MO.getReg();
114   assert(TargetRegisterInfo::isVirtualRegister(RegNo) &&
115          "Unlowered physical register encountered during assembly printing");
116   assert(!MFI->isVRegStackified(RegNo));
117   unsigned WAReg = MFI->getWAReg(RegNo);
118   assert(WAReg != WebAssemblyFunctionInfo::UnusedReg);
119   return '$' + utostr(WAReg);
120 }
121 
122 WebAssemblyTargetStreamer *WebAssemblyAsmPrinter::getTargetStreamer() {
123   MCTargetStreamer *TS = OutStreamer->getTargetStreamer();
124   return static_cast<WebAssemblyTargetStreamer *>(TS);
125 }
126 
127 //===----------------------------------------------------------------------===//
128 // WebAssemblyAsmPrinter Implementation.
129 //===----------------------------------------------------------------------===//
130 
131 void WebAssemblyAsmPrinter::EmitConstantPool() {
132   assert(MF->getConstantPool()->getConstants().empty() &&
133          "WebAssembly disables constant pools");
134 }
135 
136 void WebAssemblyAsmPrinter::EmitJumpTableInfo() {
137   // Nothing to do; jump tables are incorporated into the instruction stream.
138 }
139 
140 static void ComputeLegalValueVTs(const Function &F, const TargetMachine &TM,
141                                  Type *Ty, SmallVectorImpl<MVT> &ValueVTs) {
142   const DataLayout &DL(F.getParent()->getDataLayout());
143   const WebAssemblyTargetLowering &TLI =
144       *TM.getSubtarget<WebAssemblySubtarget>(F).getTargetLowering();
145   SmallVector<EVT, 4> VTs;
146   ComputeValueVTs(TLI, DL, Ty, VTs);
147 
148   for (EVT VT : VTs) {
149     unsigned NumRegs = TLI.getNumRegisters(F.getContext(), VT);
150     MVT RegisterVT = TLI.getRegisterType(F.getContext(), VT);
151     for (unsigned i = 0; i != NumRegs; ++i)
152       ValueVTs.push_back(RegisterVT);
153   }
154 }
155 
156 void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
157   if (!MFI->getParams().empty())
158     getTargetStreamer()->emitParam(MFI->getParams());
159 
160   SmallVector<MVT, 4> ResultVTs;
161   const Function &F(*MF->getFunction());
162   ComputeLegalValueVTs(F, TM, F.getReturnType(), ResultVTs);
163 
164   // If the return type needs to be legalized it will get converted into
165   // passing a pointer.
166   if (ResultVTs.size() == 1)
167     getTargetStreamer()->emitResult(ResultVTs);
168 
169   bool AnyWARegs = false;
170   SmallVector<MVT, 16> LocalTypes;
171   for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
172     unsigned VReg = TargetRegisterInfo::index2VirtReg(Idx);
173     unsigned WAReg = MFI->getWAReg(VReg);
174     // Don't declare unused registers.
175     if (WAReg == WebAssemblyFunctionInfo::UnusedReg)
176       continue;
177     // Don't redeclare parameters.
178     if (WAReg < MFI->getParams().size())
179       continue;
180     // Don't declare stackified registers.
181     if (int(WAReg) < 0)
182       continue;
183     LocalTypes.push_back(getRegType(VReg));
184     AnyWARegs = true;
185   }
186   auto &PhysRegs = MFI->getPhysRegs();
187   for (unsigned PReg = 0; PReg < PhysRegs.size(); ++PReg) {
188     if (PhysRegs[PReg] == -1U)
189       continue;
190     LocalTypes.push_back(getRegType(PReg));
191     AnyWARegs = true;
192   }
193   if (AnyWARegs)
194     getTargetStreamer()->emitLocal(LocalTypes);
195 
196   AsmPrinter::EmitFunctionBodyStart();
197 }
198 
199 void WebAssemblyAsmPrinter::EmitFunctionBodyEnd() {
200   getTargetStreamer()->emitEndFunc();
201 }
202 
203 void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
204   DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
205 
206   switch (MI->getOpcode()) {
207   case WebAssembly::ARGUMENT_I32:
208   case WebAssembly::ARGUMENT_I64:
209   case WebAssembly::ARGUMENT_F32:
210   case WebAssembly::ARGUMENT_F64:
211     // These represent values which are live into the function entry, so there's
212     // no instruction to emit.
213     break;
214   default: {
215     WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
216     MCInst TmpInst;
217     MCInstLowering.Lower(MI, TmpInst);
218     EmitToStreamer(*OutStreamer, TmpInst);
219     break;
220   }
221   }
222 }
223 
224 const MCExpr *WebAssemblyAsmPrinter::lowerConstant(const Constant *CV) {
225   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
226     if (GV->getValueType()->isFunctionTy())
227       return MCSymbolRefExpr::create(
228           getSymbol(GV), MCSymbolRefExpr::VK_WebAssembly_FUNCTION, OutContext);
229   return AsmPrinter::lowerConstant(CV);
230 }
231 
232 bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
233                                             unsigned OpNo, unsigned AsmVariant,
234                                             const char *ExtraCode,
235                                             raw_ostream &OS) {
236   if (AsmVariant != 0)
237     report_fatal_error("There are no defined alternate asm variants");
238 
239   // First try the generic code, which knows about modifiers like 'c' and 'n'.
240   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, OS))
241     return false;
242 
243   if (!ExtraCode) {
244     const MachineOperand &MO = MI->getOperand(OpNo);
245     switch (MO.getType()) {
246     case MachineOperand::MO_Immediate:
247       OS << MO.getImm();
248       return false;
249     case MachineOperand::MO_Register:
250       OS << regToString(MO);
251       return false;
252     case MachineOperand::MO_GlobalAddress:
253       getSymbol(MO.getGlobal())->print(OS, MAI);
254       printOffset(MO.getOffset(), OS);
255       return false;
256     case MachineOperand::MO_ExternalSymbol:
257       GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI);
258       printOffset(MO.getOffset(), OS);
259       return false;
260     case MachineOperand::MO_MachineBasicBlock:
261       MO.getMBB()->getSymbol()->print(OS, MAI);
262       return false;
263     default:
264       break;
265     }
266   }
267 
268   return true;
269 }
270 
271 bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
272                                                   unsigned OpNo,
273                                                   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   if (!ExtraCode) {
280     // TODO: For now, we just hard-code 0 as the constant offset; teach
281     // SelectInlineAsmMemoryOperand how to do address mode matching.
282     OS << "0(" + regToString(MI->getOperand(OpNo)) + ')';
283     return false;
284   }
285 
286   return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, AsmVariant, ExtraCode, OS);
287 }
288 
289 // Force static initialization.
290 extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
291   RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32);
292   RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64);
293 }
294