[WebAssembly] Switch to MC for instruction printing.
[oota-llvm.git] / lib / Target / WebAssembly / WebAssemblyAsmPrinter.cpp
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 "WebAssemblyMCInstLower.h"
21 #include "WebAssemblyMachineFunctionInfo.h"
22 #include "WebAssemblyRegisterInfo.h"
23 #include "WebAssemblySubtarget.h"
24 #include "llvm/ADT/SmallString.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
38 using namespace llvm;
39
40 #define DEBUG_TYPE "asm-printer"
41
42 namespace {
43
44 class WebAssemblyAsmPrinter final : public AsmPrinter {
45   const MachineRegisterInfo *MRI;
46   const WebAssemblyFunctionInfo *MFI;
47
48 public:
49   WebAssemblyAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
50       : AsmPrinter(TM, std::move(Streamer)), MRI(nullptr), MFI(nullptr) {}
51
52 private:
53   const char *getPassName() const override {
54     return "WebAssembly Assembly Printer";
55   }
56
57   //===------------------------------------------------------------------===//
58   // MachineFunctionPass Implementation.
59   //===------------------------------------------------------------------===//
60
61   void getAnalysisUsage(AnalysisUsage &AU) const override {
62     AsmPrinter::getAnalysisUsage(AU);
63   }
64
65   bool runOnMachineFunction(MachineFunction &MF) override {
66     MRI = &MF.getRegInfo();
67     MFI = MF.getInfo<WebAssemblyFunctionInfo>();
68     return AsmPrinter::runOnMachineFunction(MF);
69   }
70
71   //===------------------------------------------------------------------===//
72   // AsmPrinter Implementation.
73   //===------------------------------------------------------------------===//
74
75   void EmitJumpTableInfo() override;
76   void EmitConstantPool() override;
77   void EmitFunctionBodyStart() override;
78   void EmitInstruction(const MachineInstr *MI) override;
79   void EmitEndOfAsmFile(Module &M) override;
80
81   std::string getRegTypeName(unsigned RegNo) const;
82   const char *toString(MVT VT) const;
83   std::string regToString(const MachineOperand &MO);
84 };
85
86 } // end anonymous namespace
87
88 //===----------------------------------------------------------------------===//
89 // Helpers.
90 //===----------------------------------------------------------------------===//
91
92 std::string WebAssemblyAsmPrinter::getRegTypeName(unsigned RegNo) const {
93   const TargetRegisterClass *TRC = MRI->getRegClass(RegNo);
94   for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
95     if (TRC->hasType(T))
96       return EVT(T).getEVTString();
97   DEBUG(errs() << "Unknown type for register number: " << RegNo);
98   llvm_unreachable("Unknown register type");
99   return "?";
100 }
101
102 std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
103   unsigned RegNo = MO.getReg();
104   if (TargetRegisterInfo::isPhysicalRegister(RegNo))
105     return WebAssemblyInstPrinter::getRegisterName(RegNo);
106
107   return utostr(MFI->getWAReg(RegNo));
108 }
109
110 const char *WebAssemblyAsmPrinter::toString(MVT VT) const {
111   switch (VT.SimpleTy) {
112   default:
113     break;
114   case MVT::f32:
115     return "f32";
116   case MVT::f64:
117     return "f64";
118   case MVT::i32:
119     return "i32";
120   case MVT::i64:
121     return "i64";
122   }
123   DEBUG(dbgs() << "Invalid type " << EVT(VT).getEVTString() << '\n');
124   llvm_unreachable("invalid type");
125   return "<invalid>";
126 }
127
128 //===----------------------------------------------------------------------===//
129 // WebAssemblyAsmPrinter Implementation.
130 //===----------------------------------------------------------------------===//
131
132 void WebAssemblyAsmPrinter::EmitConstantPool() {
133   assert(MF->getConstantPool()->getConstants().empty() &&
134          "WebAssembly disables constant pools");
135 }
136
137 void WebAssemblyAsmPrinter::EmitJumpTableInfo() {
138   // Nothing to do; jump tables are incorporated into the instruction stream.
139 }
140
141 void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
142   SmallString<128> Str;
143   raw_svector_ostream OS(Str);
144
145   for (MVT VT : MFI->getParams())
146     OS << "\t" ".param " << toString(VT) << '\n';
147   for (MVT VT : MFI->getResults())
148     OS << "\t" ".result " << toString(VT) << '\n';
149
150   bool FirstVReg = true;
151   for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
152     unsigned VReg = TargetRegisterInfo::index2VirtReg(Idx);
153     if (!MRI->use_empty(VReg)) {
154       if (FirstVReg)
155         OS << "\t" ".local ";
156       else
157         OS << ", ";
158       OS << getRegTypeName(VReg);
159       FirstVReg = false;
160     }
161   }
162   if (!FirstVReg)
163     OS << '\n';
164
165   // EmitRawText appends a newline, so strip off the last newline.
166   StringRef Text = OS.str();
167   if (!Text.empty())
168     OutStreamer->EmitRawText(Text.substr(0, Text.size() - 1));
169   AsmPrinter::EmitFunctionBodyStart();
170 }
171
172 void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
173   DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
174
175   unsigned NumDefs = MI->getDesc().getNumDefs();
176   assert(NumDefs <= 1 &&
177          "Instructions with multiple result values not implemented");
178
179   switch (MI->getOpcode()) {
180   case TargetOpcode::COPY: {
181     // TODO: Figure out a way to lower COPY instructions to MCInst form.
182     SmallString<128> Str;
183     raw_svector_ostream OS(Str);
184     OS << "\t" "set_local " << regToString(MI->getOperand(0)) << ", "
185                "(get_local " << regToString(MI->getOperand(1)) << ")";
186     OutStreamer->EmitRawText(OS.str());
187     break;
188   }
189   case WebAssembly::ARGUMENT_I32:
190   case WebAssembly::ARGUMENT_I64:
191   case WebAssembly::ARGUMENT_F32:
192   case WebAssembly::ARGUMENT_F64:
193     // These represent values which are live into the function entry, so there's
194     // no instruction to emit.
195     break;
196   default: {
197     WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
198     MCInst TmpInst;
199     MCInstLowering.Lower(MI, TmpInst);
200     EmitToStreamer(*OutStreamer, TmpInst);
201     break;
202   }
203   }
204 }
205
206 static void ComputeLegalValueVTs(LLVMContext &Context,
207                                  const WebAssemblyTargetLowering &TLI,
208                                  const DataLayout &DL, Type *Ty,
209                                  SmallVectorImpl<MVT> &ValueVTs) {
210   SmallVector<EVT, 4> VTs;
211   ComputeValueVTs(TLI, DL, Ty, VTs);
212
213   for (EVT VT : VTs) {
214     unsigned NumRegs = TLI.getNumRegisters(Context, VT);
215     MVT RegisterVT = TLI.getRegisterType(Context, VT);
216     for (unsigned i = 0; i != NumRegs; ++i)
217       ValueVTs.push_back(RegisterVT);
218   }
219 }
220
221 void WebAssemblyAsmPrinter::EmitEndOfAsmFile(Module &M) {
222   const DataLayout &DL = M.getDataLayout();
223
224   SmallString<128> Str;
225   raw_svector_ostream OS(Str);
226   for (const Function &F : M)
227     if (F.isDeclarationForLinker()) {
228       assert(F.hasName() && "imported functions must have a name");
229       if (F.isIntrinsic())
230         continue;
231       if (Str.empty())
232         OS << "\t.imports\n";
233
234       MCSymbol *Sym = OutStreamer->getContext().getOrCreateSymbol(F.getName());
235       OS << "\t.import " << *Sym << " \"\" " << *Sym;
236
237       const WebAssemblyTargetLowering &TLI =
238           *TM.getSubtarget<WebAssemblySubtarget>(F).getTargetLowering();
239
240       // If we need to legalize the return type, it'll get converted into
241       // passing a pointer.
242       bool SawParam = false;
243       SmallVector<MVT, 4> ResultVTs;
244       ComputeLegalValueVTs(M.getContext(), TLI, DL, F.getReturnType(),
245                            ResultVTs);
246       if (ResultVTs.size() > 1) {
247         ResultVTs.clear();
248         OS << " (param " << toString(TLI.getPointerTy(DL));
249         SawParam = true;
250       }
251
252       for (const Argument &A : F.args()) {
253         SmallVector<MVT, 4> ParamVTs;
254         ComputeLegalValueVTs(M.getContext(), TLI, DL, A.getType(), ParamVTs);
255         for (EVT VT : ParamVTs) {
256           if (!SawParam) {
257             OS << " (param";
258             SawParam = true;
259           }
260           OS << ' ' << toString(VT.getSimpleVT());
261         }
262       }
263       if (SawParam)
264         OS << ')';
265
266       for (EVT VT : ResultVTs)
267         OS << " (result " << toString(VT.getSimpleVT()) << ')';
268
269       OS << '\n';
270     }
271
272   StringRef Text = OS.str();
273   if (!Text.empty())
274     OutStreamer->EmitRawText(Text.substr(0, Text.size() - 1));
275 }
276
277 // Force static initialization.
278 extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
279   RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32);
280   RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64);
281 }