LLVM  7.0.0
WebAssemblyAsmPrinter.cpp
Go to the documentation of this file.
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 /// 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"
21 #include "WebAssembly.h"
22 #include "WebAssemblyMCInstLower.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/Analysis.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/MC/MCContext.h"
34 #include "llvm/MC/MCSectionWasm.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/MC/MCSymbolWasm.h"
38 #include "llvm/Support/Debug.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);
54  if (TRI->isTypeLegalForClass(*TRC, T))
55  return T;
56  LLVM_DEBUG(errs() << "Unknown type for register number: " << RegNo);
57  llvm_unreachable("Unknown register type");
58  return MVT::Other;
59 }
60 
62  unsigned RegNo = MO.getReg();
64  "Unlowered physical register encountered during assembly printing");
65  assert(!MFI->isVRegStackified(RegNo));
66  unsigned WAReg = MFI->getWAReg(RegNo);
68  return '$' + utostr(WAReg);
69 }
70 
72  MCTargetStreamer *TS = OutStreamer->getTargetStreamer();
73  return static_cast<WebAssemblyTargetStreamer *>(TS);
74 }
75 
76 //===----------------------------------------------------------------------===//
77 // WebAssemblyAsmPrinter Implementation.
78 //===----------------------------------------------------------------------===//
79 
81  for (const auto &F : M) {
82  // Emit function type info for all undefined functions
83  if (F.isDeclarationForLinker() && !F.isIntrinsic()) {
85  SmallVector<MVT, 4> Params;
86  ComputeSignatureVTs(F, TM, Params, Results);
87  MCSymbol *Sym = getSymbol(&F);
88  getTargetStreamer()->emitIndirectFunctionType(Sym, Params, Results);
89 
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  OutStreamer->emitELFSize(getSymbol(&G),
105  }
106  }
107  }
108 
109  if (const NamedMDNode *Named = M.getNamedMetadata("wasm.custom_sections")) {
110  for (const Metadata *MD : Named->operands()) {
111  const MDTuple *Tuple = dyn_cast<MDTuple>(MD);
112  if (!Tuple || Tuple->getNumOperands() != 2)
113  continue;
114  const MDString *Name = dyn_cast<MDString>(Tuple->getOperand(0));
115  const MDString *Contents = dyn_cast<MDString>(Tuple->getOperand(1));
116  if (!Name || !Contents)
117  continue;
118 
119  OutStreamer->PushSection();
120  std::string SectionName = (".custom_section." + Name->getString()).str();
121  MCSectionWasm *mySection =
123  OutStreamer->SwitchSection(mySection);
124  OutStreamer->EmitBytes(Contents->getString());
125  OutStreamer->PopSection();
126  }
127  }
128 }
129 
131  assert(MF->getConstantPool()->getConstants().empty() &&
132  "WebAssembly disables constant pools");
133 }
134 
136  // Nothing to do; jump tables are incorporated into the instruction stream.
137 }
138 
141 
142  SmallVector<MVT, 4> ResultVTs;
143  const Function &F = MF->getFunction();
144 
145  // Emit the function index.
146  if (MDNode *Idx = F.getMetadata("wasm.index")) {
147  assert(Idx->getNumOperands() == 1);
148 
150  cast<ConstantAsMetadata>(Idx->getOperand(0))->getValue()));
151  }
152 
153  ComputeLegalValueVTs(F, TM, F.getReturnType(), ResultVTs);
154 
155  // If the return type needs to be legalized it will get converted into
156  // passing a pointer.
157  if (ResultVTs.size() == 1)
159  else
161 
163 
165 }
166 
168  LLVM_DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
169 
170  switch (MI->getOpcode()) {
171  case WebAssembly::ARGUMENT_I32:
172  case WebAssembly::ARGUMENT_I64:
173  case WebAssembly::ARGUMENT_F32:
174  case WebAssembly::ARGUMENT_F64:
175  case WebAssembly::ARGUMENT_v16i8:
176  case WebAssembly::ARGUMENT_v8i16:
177  case WebAssembly::ARGUMENT_v4i32:
178  case WebAssembly::ARGUMENT_v4f32:
179  // These represent values which are live into the function entry, so there's
180  // no instruction to emit.
181  break;
182  case WebAssembly::FALLTHROUGH_RETURN_I32:
183  case WebAssembly::FALLTHROUGH_RETURN_I64:
184  case WebAssembly::FALLTHROUGH_RETURN_F32:
185  case WebAssembly::FALLTHROUGH_RETURN_F64:
186  case WebAssembly::FALLTHROUGH_RETURN_v16i8:
187  case WebAssembly::FALLTHROUGH_RETURN_v8i16:
188  case WebAssembly::FALLTHROUGH_RETURN_v4i32:
189  case WebAssembly::FALLTHROUGH_RETURN_v4f32: {
190  // These instructions represent the implicit return at the end of a
191  // function body. The operand is always a pop.
192  assert(MFI->isVRegStackified(MI->getOperand(0).getReg()));
193 
194  if (isVerbose()) {
195  OutStreamer->AddComment("fallthrough-return: $pop" +
196  Twine(MFI->getWARegStackId(
197  MFI->getWAReg(MI->getOperand(0).getReg()))));
198  OutStreamer->AddBlankLine();
199  }
200  break;
201  }
202  case WebAssembly::FALLTHROUGH_RETURN_VOID:
203  // This instruction represents the implicit return at the end of a
204  // function body with no return value.
205  if (isVerbose()) {
206  OutStreamer->AddComment("fallthrough-return");
207  OutStreamer->AddBlankLine();
208  }
209  break;
210  default: {
211  WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
212  MCInst TmpInst;
213  MCInstLowering.Lower(MI, TmpInst);
214  EmitToStreamer(*OutStreamer, TmpInst);
215  break;
216  }
217  }
218 }
219 
221  if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
222  if (GV->getValueType()->isFunctionTy()) {
225  }
226  return AsmPrinter::lowerConstant(CV);
227 }
228 
230  unsigned OpNo, unsigned AsmVariant,
231  const char *ExtraCode,
232  raw_ostream &OS) {
233  if (AsmVariant != 0)
234  report_fatal_error("There are no defined alternate asm variants");
235 
236  // First try the generic code, which knows about modifiers like 'c' and 'n'.
237  if (!AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, OS))
238  return false;
239 
240  if (!ExtraCode) {
241  const MachineOperand &MO = MI->getOperand(OpNo);
242  switch (MO.getType()) {
244  OS << MO.getImm();
245  return false;
247  OS << regToString(MO);
248  return false;
250  getSymbol(MO.getGlobal())->print(OS, MAI);
251  printOffset(MO.getOffset(), OS);
252  return false;
255  printOffset(MO.getOffset(), OS);
256  return false;
258  MO.getMBB()->getSymbol()->print(OS, MAI);
259  return false;
260  default:
261  break;
262  }
263  }
264 
265  return true;
266 }
267 
269  unsigned OpNo,
270  unsigned AsmVariant,
271  const char *ExtraCode,
272  raw_ostream &OS) {
273  if (AsmVariant != 0)
274  report_fatal_error("There are no defined alternate asm variants");
275 
276  // The current approach to inline asm is that "r" constraints are expressed
277  // as local indices, rather than values on the operand stack. This simplifies
278  // using "r" as it eliminates the need to push and pop the values in a
279  // particular order, however it also makes it impossible to have an "m"
280  // constraint. So we don't support it.
281 
282  return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, AsmVariant, ExtraCode, OS);
283 }
284 
285 // Force static initialization.
289 }
virtual void emitImportModule(MCSymbolWasm *Sym, StringRef ModuleName)=0
.import_module
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
MachineBasicBlock * getMBB() const
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition: AsmPrinter.h:93
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
MCSymbol * GetExternalSymbolSymbol(StringRef Sym) const
Return the MCSymbol for the specified ExternalSymbol.
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:321
This class is used to lower an MachineInstr into an MCInst.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:119
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
const std::vector< MVT > & getLocals() const
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:42
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition: AsmPrinter.h:88
This class prints an WebAssembly MCInst to wasm file syntax.
unsigned getReg() const
getReg - Returns the register number.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
Target specific streamer interface.
Definition: MCStreamer.h:83
MCSectionWasm * getWasmSection(const Twine &Section, SectionKind K)
Definition: MCContext.h:458
This file declares the class to lower WebAssembly MachineInstrs to their corresponding MCInst records...
void EmitInstruction(const MachineInstr *MI) override
Targets should implement this to emit instructions.
Function Alias Analysis Results
MachineBasicBlock reference.
unsigned const TargetRegisterInfo * TRI
Metadata node.
Definition: Metadata.h:862
F(f)
MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:96
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1067
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end...
Tuple of metadata.
Definition: Metadata.h:1104
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
A tuple of MDNodes.
Definition: Metadata.h:1323
MVT getRegType(unsigned RegNo) const
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
void ComputeLegalValueVTs(const Function &F, const TargetMachine &TM, Type *Ty, SmallVectorImpl< MVT > &ValueVTs)
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:36
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Metadata.cpp:1444
Name of external global symbol.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:311
const char * getSymbolName() const
bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS) override
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant...
std::string regToString(const MachineOperand &MO)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant as...
RegisterAsmPrinter - Helper template for registering a target specific assembly printer, for use in the target machine initialization function.
void printOffset(int64_t Offset, raw_ostream &OS) const
This is just convenient handler for printing offsets.
bool isVerbose() const
Return true if assembly output should contain comments.
Definition: AsmPrinter.h:199
bool isTypeLegalForClass(const TargetRegisterClass &RC, MVT T) const
Return true if the given TargetRegisterClass has the ValueType T.
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:161
WebAssembly-specific streamer interface, to implement support WebAssembly-specific assembly directive...
StringRef getString() const
Definition: Metadata.cpp:464
Address of a global value.
Type * getReturnType() const
Returns the type of the ret val.
Definition: Function.h:155
MCSymbol * CurrentFnSym
The symbol for the current function.
Definition: AsmPrinter.h:112
Machine Value Type.
const MCAsmInfo * MAI
Target Asm Printer information.
Definition: AsmPrinter.h:84
virtual void emitResult(MCSymbol *Symbol, ArrayRef< MVT > Types)=0
.result
void ComputeSignatureVTs(const Function &F, const TargetMachine &TM, SmallVectorImpl< MVT > &Params, SmallVectorImpl< MVT > &Results)
This is an important base class in LLVM.
Definition: Constant.h:42
void EmitEndOfAsmFile(Module &M) override
This virtual method can be overridden by targets that want to emit something at the end of their file...
This represents a section on wasm.
Definition: MCSectionWasm.h:28
const GlobalValue * getGlobal() const
virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant...
This file provides WebAssembly-specific target descriptions.
TargetMachine & TM
Target machine description.
Definition: AsmPrinter.h:81
const Triple & getTargetTriple() const
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
const MCExpr * lowerConstant(const Constant *CV) override
Lower the specified LLVM Constant to an MCExpr.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
size_t size() const
Definition: SmallVector.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This file declares WebAssembly-specific target streamer classes.
const std::vector< MachineConstantPoolEntry > & getConstants() const
void Lower(const MachineInstr *MI, MCInst &OutMI) const
This file contains the WebAssembly implementation of the WebAssemblyRegisterInfo class.
void LLVMInitializeWebAssemblyAsmPrinter()
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:427
virtual const MCExpr * lowerConstant(const Constant *CV)
Lower the specified LLVM Constant to an MCExpr.
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
const DataFlowGraph & G
Definition: RDFGraph.cpp:211
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
Definition: AsmPrinter.cpp:228
static SectionKind getMetadata()
Definition: SectionKind.h:179
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:223
int64_t getImm() const
const Function & getFunction() const
Return the LLVM function that this machine code represents.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
virtual void EmitFunctionBodyStart()
Targets can override this to emit stuff before the first basic block in the function.
Definition: AsmPrinter.h:385
void EmitConstantPool() override
Print to the current output stream assembly representations of the constants in the constant pool MCP...
virtual void emitIndirectFunctionType(MCSymbol *Symbol, SmallVectorImpl< MVT > &Params, SmallVectorImpl< MVT > &Results)=0
.functype
const WebAssemblyRegisterInfo * getRegisterInfo() const override
void EmitJumpTableInfo() override
Print assembly representations of the jump tables used by the current function to the current output ...
Representation of each machine instruction.
Definition: MachineInstr.h:60
int64_t getOffset() const
Return the offset from the symbol in this operand.
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
This file declares WebAssembly-specific per-machine-function information.
virtual void print(raw_ostream &OS, const Module *M) const
print - Print out the internal state of the pass.
Definition: Pass.cpp:124
void EmitFunctionBodyStart() override
Targets can override this to emit stuff before the first basic block in the function.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
unsigned getWAReg(unsigned VReg) const
virtual void emitParam(MCSymbol *Symbol, ArrayRef< MVT > Types)=0
.param
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS) override
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant as...
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
virtual void emitLocal(ArrayRef< MVT > Types)=0
.local
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
A single uniqued string.
Definition: Metadata.h:602
const std::vector< MVT > & getParams() const
Target & getTheWebAssemblyTarget32()
bool isOSBinFormatWasm() const
Tests whether the OS uses the Wasm binary format.
Definition: Triple.h:603
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1073
#define LLVM_DEBUG(X)
Definition: Debug.h:119
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:316
Target & getTheWebAssemblyTarget64()
WebAssemblyTargetStreamer * getTargetStreamer()
Root of the metadata hierarchy.
Definition: Metadata.h:58
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx)
Definition: MCExpr.cpp:164
virtual void emitIndIdx(const MCExpr *Value)=0
.indidx
static unsigned getWARegStackId(unsigned Reg)
void print(raw_ostream &OS, const MCAsmInfo *MAI) const
print - Print the value to the stream OS.
Definition: MCSymbol.cpp:60