WebAssembly: NFC comment update
[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 "WebAssemblyMachineFunctionInfo.h"
19 #include "WebAssemblyRegisterInfo.h"
20 #include "WebAssemblySubtarget.h"
21 #include "InstPrinter/WebAssemblyInstPrinter.h"
22 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
23
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/CodeGen/AsmPrinter.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/raw_ostream.h"
35
36 using namespace llvm;
37
38 #define DEBUG_TYPE "asm-printer"
39
40 namespace {
41
42 class WebAssemblyAsmPrinter final : public AsmPrinter {
43   const WebAssemblyInstrInfo *TII;
44
45 public:
46   WebAssemblyAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
47       : AsmPrinter(TM, std::move(Streamer)), TII(nullptr) {}
48
49 private:
50   const char *getPassName() const override {
51     return "WebAssembly Assembly Printer";
52   }
53
54   //===------------------------------------------------------------------===//
55   // MachineFunctionPass Implementation.
56   //===------------------------------------------------------------------===//
57
58   void getAnalysisUsage(AnalysisUsage &AU) const override {
59     AsmPrinter::getAnalysisUsage(AU);
60   }
61
62   bool runOnMachineFunction(MachineFunction &MF) override {
63     TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
64     return AsmPrinter::runOnMachineFunction(MF);
65   }
66
67   //===------------------------------------------------------------------===//
68   // AsmPrinter Implementation.
69   //===------------------------------------------------------------------===//
70
71   void EmitGlobalVariable(const GlobalVariable *GV) override;
72
73   void EmitConstantPool() override;
74   void EmitFunctionEntryLabel() override;
75   void EmitFunctionBodyStart() override;
76   void EmitFunctionBodyEnd() override;
77
78   void EmitInstruction(const MachineInstr *MI) override;
79 };
80
81 } // end anonymous namespace
82
83 //===----------------------------------------------------------------------===//
84 // Helpers.
85 //===----------------------------------------------------------------------===//
86
87 // Untyped, lower-case version of the opcode's name matching the names
88 // WebAssembly opcodes are expected to have. The tablegen names are uppercase
89 // and suffixed with their type (after an underscore).
90 static SmallString<32> OpcodeName(const WebAssemblyInstrInfo *TII,
91                                   const MachineInstr *MI) {
92   std::string N(StringRef(TII->getName(MI->getOpcode())).lower());
93   std::string::size_type End = N.rfind('_');
94   End = std::string::npos == End ? N.length() : End;
95   return SmallString<32>(&N[0], &N[End]);
96 }
97
98 static std::string toSymbol(StringRef S) { return ("$" + S).str(); }
99
100 static const char *toString(const Type *Ty) {
101   switch (Ty->getTypeID()) {
102   default: break;
103   case Type::FloatTyID:  return "f32";
104   case Type::DoubleTyID: return "f64";
105   case Type::IntegerTyID:
106     switch (Ty->getIntegerBitWidth()) {
107     case 32: return "i32";
108     case 64: return "i64";
109     default: break;
110     }
111   }
112   DEBUG(dbgs() << "Invalid type "; Ty->print(dbgs()); dbgs() << '\n');
113   llvm_unreachable("invalid type");
114   return "<invalid>";
115 }
116
117 static std::string toString(const APFloat &FP) {
118   static const size_t BufBytes = 128;
119   char buf[BufBytes];
120   if (FP.isNaN())
121     assert((FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) ||
122             FP.bitwiseIsEqual(
123                 APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) &&
124            "convertToHexString handles neither SNaN nor NaN payloads");
125   // Use C99's hexadecimal floating-point representation.
126   auto Written = FP.convertToHexString(
127       buf, /*hexDigits=*/0, /*upperCase=*/false, APFloat::rmNearestTiesToEven);
128   (void)Written;
129   assert(Written != 0);
130   assert(Written < BufBytes);
131   return buf;
132 }
133
134 //===----------------------------------------------------------------------===//
135 // WebAssemblyAsmPrinter Implementation.
136 //===----------------------------------------------------------------------===//
137
138 void WebAssemblyAsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
139   SmallString<128> Str;
140   raw_svector_ostream OS(Str);
141   StringRef Name = GV->getName();
142   DEBUG(dbgs() << "Global " << Name << '\n');
143
144   if (!GV->hasInitializer()) {
145     DEBUG(dbgs() << "  Skipping declaration.\n");
146     return;
147   }
148
149   // Check to see if this is a special global used by LLVM.
150   static const char *Ignored[] = {"llvm.used", "llvm.metadata"};
151   for (const char *I : Ignored)
152     if (Name == I)
153       return;
154   // FIXME: Handle the following globals.
155   static const char *Unhandled[] = {"llvm.global_ctors", "llvm.global_dtors"};
156   for (const char *U : Unhandled)
157     if (Name == U)
158       report_fatal_error("Unhandled global");
159   if (Name.startswith("llvm."))
160     report_fatal_error("Unknown LLVM-internal global");
161
162   if (GV->isThreadLocal())
163     report_fatal_error("TLS isn't yet supported by WebAssembly");
164
165   const DataLayout &DL = getDataLayout();
166   const Constant *Init = GV->getInitializer();
167   if (isa<UndefValue>(Init))
168     Init = Constant::getNullValue(Init->getType());
169   unsigned Align = DL.getPrefTypeAlignment(Init->getType());
170
171   switch (GV->getLinkage()) {
172   case GlobalValue::InternalLinkage:
173   case GlobalValue::PrivateLinkage:
174     break;
175   case GlobalValue::AppendingLinkage:
176   case GlobalValue::LinkOnceAnyLinkage:
177   case GlobalValue::LinkOnceODRLinkage:
178   case GlobalValue::WeakAnyLinkage:
179   case GlobalValue::WeakODRLinkage:
180   case GlobalValue::ExternalLinkage:
181   case GlobalValue::CommonLinkage:
182     report_fatal_error("Linkage types other than internal and private aren't "
183                        "supported by WebAssembly yet");
184   default:
185     llvm_unreachable("Unknown linkage type");
186     return;
187   }
188
189   OS << "(global " << toSymbol(Name) << ' ' << toString(Init->getType()) << ' ';
190   if (const auto *C = dyn_cast<ConstantInt>(Init)) {
191     assert(C->getBitWidth() <= 64 && "Printing wider types unimplemented");
192     OS << C->getZExtValue();
193   } else if (const auto *C = dyn_cast<ConstantFP>(Init)) {
194     OS << toString(C->getValueAPF());
195   } else {
196     assert(false && "Only integer and floating-point constants are supported");
197   }
198   OS << ") ;; align " << Align << "\n";
199   OutStreamer->EmitRawText(OS.str());
200 }
201
202 void WebAssemblyAsmPrinter::EmitConstantPool() {
203   assert(MF->getConstantPool()->getConstants().empty() &&
204          "WebAssembly disables constant pools");
205 }
206
207 void WebAssemblyAsmPrinter::EmitFunctionEntryLabel() {
208   SmallString<128> Str;
209   raw_svector_ostream OS(Str);
210
211   CurrentFnSym->redefineIfPossible();
212
213   // The function label could have already been emitted if two symbols end up
214   // conflicting due to asm renaming.  Detect this and emit an error.
215   if (CurrentFnSym->isVariable())
216     report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
217                        "' is a protected alias");
218   if (CurrentFnSym->isDefined())
219     report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
220                        "' label emitted multiple times to assembly file");
221
222   OS << "(func " << toSymbol(CurrentFnSym->getName());
223   OutStreamer->EmitRawText(OS.str());
224 }
225
226 void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
227   SmallString<128> Str;
228   raw_svector_ostream OS(Str);
229   const Function *F = MF->getFunction();
230   for (const Argument &A : F->args())
231     OS << " (param " << toString(A.getType()) << ')';
232   const Type *Rt = F->getReturnType();
233   if (!Rt->isVoidTy())
234     OS << " (result " << toString(Rt) << ')';
235   OS << '\n';
236   OutStreamer->EmitRawText(OS.str());
237 }
238
239 void WebAssemblyAsmPrinter::EmitFunctionBodyEnd() {
240   SmallString<128> Str;
241   raw_svector_ostream OS(Str);
242   OS << ") ;; end func " << toSymbol(CurrentFnSym->getName()) << '\n';
243   OutStreamer->EmitRawText(OS.str());
244 }
245
246 void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
247   DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
248   SmallString<128> Str;
249   raw_svector_ostream OS(Str);
250
251   unsigned NumDefs = MI->getDesc().getNumDefs();
252   assert(NumDefs <= 1 &&
253          "Instructions with multiple result values not implemented");
254
255   OS << '\t';
256
257   if (NumDefs != 0) {
258     const MachineOperand &MO = MI->getOperand(0);
259     unsigned Reg = MO.getReg();
260     OS << "(setlocal @" << TargetRegisterInfo::virtReg2Index(Reg) << ' ';
261   }
262
263   OS << '(' << OpcodeName(TII, MI);
264   for (const MachineOperand &MO : MI->uses())
265     switch (MO.getType()) {
266     default:
267       llvm_unreachable("unexpected machine operand type");
268     case MachineOperand::MO_Register: {
269       if (MO.isImplicit())
270         continue;
271       unsigned Reg = MO.getReg();
272       OS << " @" << TargetRegisterInfo::virtReg2Index(Reg);
273     } break;
274     case MachineOperand::MO_Immediate: {
275       OS << ' ' << MO.getImm();
276     } break;
277     case MachineOperand::MO_FPImmediate: {
278       OS << ' ' << toString(MO.getFPImm()->getValueAPF());
279     } break;
280     case MachineOperand::MO_GlobalAddress: {
281       OS << ' ' << toSymbol(MO.getGlobal()->getName());
282     } break;
283     }
284   OS << ')';
285
286   if (NumDefs != 0)
287     OS << ')';
288
289   OS << '\n';
290
291   OutStreamer->EmitRawText(OS.str());
292 }
293
294 // Force static initialization.
295 extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
296   RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32);
297   RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64);
298 }