LLVM  9.0.0svn
WebAssemblyAsmParser.cpp
Go to the documentation of this file.
1 //==- WebAssemblyAsmParser.cpp - Assembler for WebAssembly -*- C++ -*-==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file is part of the WebAssembly Assembler.
11 ///
12 /// It contains code to translate a parsed .s file into MCInsts.
13 ///
14 //===----------------------------------------------------------------------===//
15 
19 #include "WebAssembly.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCInstrInfo.h"
26 #include "llvm/MC/MCSectionWasm.h"
27 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/MC/MCSymbolWasm.h"
31 #include "llvm/Support/Endian.h"
33 
34 using namespace llvm;
35 
36 #define DEBUG_TYPE "wasm-asm-parser"
37 
38 namespace {
39 
40 /// WebAssemblyOperand - Instances of this class represent the operands in a
41 /// parsed WASM machine instruction.
42 struct WebAssemblyOperand : public MCParsedAsmOperand {
43  enum KindTy { Token, Integer, Float, Symbol, BrList } Kind;
44 
45  SMLoc StartLoc, EndLoc;
46 
47  struct TokOp {
48  StringRef Tok;
49  };
50 
51  struct IntOp {
52  int64_t Val;
53  };
54 
55  struct FltOp {
56  double Val;
57  };
58 
59  struct SymOp {
60  const MCExpr *Exp;
61  };
62 
63  struct BrLOp {
64  std::vector<unsigned> List;
65  };
66 
67  union {
68  struct TokOp Tok;
69  struct IntOp Int;
70  struct FltOp Flt;
71  struct SymOp Sym;
72  struct BrLOp BrL;
73  };
74 
75  WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, TokOp T)
76  : Kind(K), StartLoc(Start), EndLoc(End), Tok(T) {}
77  WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, IntOp I)
78  : Kind(K), StartLoc(Start), EndLoc(End), Int(I) {}
79  WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, FltOp F)
80  : Kind(K), StartLoc(Start), EndLoc(End), Flt(F) {}
81  WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, SymOp S)
82  : Kind(K), StartLoc(Start), EndLoc(End), Sym(S) {}
83  WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End)
84  : Kind(K), StartLoc(Start), EndLoc(End), BrL() {}
85 
86  ~WebAssemblyOperand() {
87  if (isBrList())
88  BrL.~BrLOp();
89  }
90 
91  bool isToken() const override { return Kind == Token; }
92  bool isImm() const override {
93  return Kind == Integer || Kind == Float || Kind == Symbol;
94  }
95  bool isMem() const override { return false; }
96  bool isReg() const override { return false; }
97  bool isBrList() const { return Kind == BrList; }
98 
99  unsigned getReg() const override {
100  llvm_unreachable("Assembly inspects a register operand");
101  return 0;
102  }
103 
104  StringRef getToken() const {
105  assert(isToken());
106  return Tok.Tok;
107  }
108 
109  SMLoc getStartLoc() const override { return StartLoc; }
110  SMLoc getEndLoc() const override { return EndLoc; }
111 
112  void addRegOperands(MCInst &, unsigned) const {
113  // Required by the assembly matcher.
114  llvm_unreachable("Assembly matcher creates register operands");
115  }
116 
117  void addImmOperands(MCInst &Inst, unsigned N) const {
118  assert(N == 1 && "Invalid number of operands!");
119  if (Kind == Integer)
121  else if (Kind == Float)
122  Inst.addOperand(MCOperand::createFPImm(Flt.Val));
123  else if (Kind == Symbol)
124  Inst.addOperand(MCOperand::createExpr(Sym.Exp));
125  else
126  llvm_unreachable("Should be immediate or symbol!");
127  }
128 
129  void addBrListOperands(MCInst &Inst, unsigned N) const {
130  assert(N == 1 && isBrList() && "Invalid BrList!");
131  for (auto Br : BrL.List)
133  }
134 
135  void print(raw_ostream &OS) const override {
136  switch (Kind) {
137  case Token:
138  OS << "Tok:" << Tok.Tok;
139  break;
140  case Integer:
141  OS << "Int:" << Int.Val;
142  break;
143  case Float:
144  OS << "Flt:" << Flt.Val;
145  break;
146  case Symbol:
147  OS << "Sym:" << Sym.Exp;
148  break;
149  case BrList:
150  OS << "BrList:" << BrL.List.size();
151  break;
152  }
153  }
154 };
155 
156 class WebAssemblyAsmParser final : public MCTargetAsmParser {
157  MCAsmParser &Parser;
158  MCAsmLexer &Lexer;
159 
160  // Much like WebAssemblyAsmPrinter in the backend, we have to own these.
161  std::vector<std::unique_ptr<wasm::WasmSignature>> Signatures;
162 
163  // Order of labels, directives and instructions in a .s file have no
164  // syntactical enforcement. This class is a callback from the actual parser,
165  // and yet we have to be feeding data to the streamer in a very particular
166  // order to ensure a correct binary encoding that matches the regular backend
167  // (the streamer does not enforce this). This "state machine" enum helps
168  // guarantee that correct order.
169  enum ParserState {
170  FileStart,
171  Label,
172  FunctionStart,
173  FunctionLocals,
174  Instructions,
175  EndFunction,
176  DataSection,
177  } CurrentState = FileStart;
178 
179  // For ensuring blocks are properly nested.
180  enum NestingType {
181  Function,
182  Block,
183  Loop,
184  Try,
185  If,
186  Else,
187  Undefined,
188  };
189  std::vector<NestingType> NestingStack;
190 
191  // We track this to see if a .functype following a label is the same,
192  // as this is how we recognize the start of a function.
193  MCSymbol *LastLabel = nullptr;
194  MCSymbol *LastFunctionLabel = nullptr;
195 
196 public:
197  WebAssemblyAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
198  const MCInstrInfo &MII, const MCTargetOptions &Options)
199  : MCTargetAsmParser(Options, STI, MII), Parser(Parser),
200  Lexer(Parser.getLexer()) {
201  setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
202  }
203 
204 #define GET_ASSEMBLER_HEADER
205 #include "WebAssemblyGenAsmMatcher.inc"
206 
207  // TODO: This is required to be implemented, but appears unused.
208  bool ParseRegister(unsigned & /*RegNo*/, SMLoc & /*StartLoc*/,
209  SMLoc & /*EndLoc*/) override {
210  llvm_unreachable("ParseRegister is not implemented.");
211  }
212 
213  bool error(const Twine &Msg, const AsmToken &Tok) {
214  return Parser.Error(Tok.getLoc(), Msg + Tok.getString());
215  }
216 
217  bool error(const Twine &Msg) {
218  return Parser.Error(Lexer.getTok().getLoc(), Msg);
219  }
220 
221  void addSignature(std::unique_ptr<wasm::WasmSignature> &&Sig) {
222  Signatures.push_back(std::move(Sig));
223  }
224 
225  std::pair<StringRef, StringRef> nestingString(NestingType NT) {
226  switch (NT) {
227  case Function:
228  return {"function", "end_function"};
229  case Block:
230  return {"block", "end_block"};
231  case Loop:
232  return {"loop", "end_loop"};
233  case Try:
234  return {"try", "end_try"};
235  case If:
236  return {"if", "end_if"};
237  case Else:
238  return {"else", "end_if"};
239  default:
240  llvm_unreachable("unknown NestingType");
241  }
242  }
243 
244  void push(NestingType NT) { NestingStack.push_back(NT); }
245 
246  bool pop(StringRef Ins, NestingType NT1, NestingType NT2 = Undefined) {
247  if (NestingStack.empty())
248  return error(Twine("End of block construct with no start: ") + Ins);
249  auto Top = NestingStack.back();
250  if (Top != NT1 && Top != NT2)
251  return error(Twine("Block construct type mismatch, expected: ") +
252  nestingString(Top).second + ", instead got: " + Ins);
253  NestingStack.pop_back();
254  return false;
255  }
256 
257  bool ensureEmptyNestingStack() {
258  auto Err = !NestingStack.empty();
259  while (!NestingStack.empty()) {
260  error(Twine("Unmatched block construct(s) at function end: ") +
261  nestingString(NestingStack.back()).first);
262  NestingStack.pop_back();
263  }
264  return Err;
265  }
266 
267  bool isNext(AsmToken::TokenKind Kind) {
268  auto Ok = Lexer.is(Kind);
269  if (Ok)
270  Parser.Lex();
271  return Ok;
272  }
273 
274  bool expect(AsmToken::TokenKind Kind, const char *KindName) {
275  if (!isNext(Kind))
276  return error(std::string("Expected ") + KindName + ", instead got: ",
277  Lexer.getTok());
278  return false;
279  }
280 
281  StringRef expectIdent() {
282  if (!Lexer.is(AsmToken::Identifier)) {
283  error("Expected identifier, got: ", Lexer.getTok());
284  return StringRef();
285  }
286  auto Name = Lexer.getTok().getString();
287  Parser.Lex();
288  return Name;
289  }
290 
292  // FIXME: can't use StringSwitch because wasm::ValType doesn't have a
293  // "invalid" value.
294  if (Type == "i32")
295  return wasm::ValType::I32;
296  if (Type == "i64")
297  return wasm::ValType::I64;
298  if (Type == "f32")
299  return wasm::ValType::F32;
300  if (Type == "f64")
301  return wasm::ValType::F64;
302  if (Type == "v128" || Type == "i8x16" || Type == "i16x8" ||
303  Type == "i32x4" || Type == "i64x2" || Type == "f32x4" ||
304  Type == "f64x2")
305  return wasm::ValType::V128;
306  if (Type == "except_ref")
308  return Optional<wasm::ValType>();
309  }
310 
311  WebAssembly::ExprType parseBlockType(StringRef ID) {
313  .Case("i32", WebAssembly::ExprType::I32)
318  .Case("except_ref", WebAssembly::ExprType::ExceptRef)
321  }
322 
323  bool parseRegTypeList(SmallVectorImpl<wasm::ValType> &Types) {
324  while (Lexer.is(AsmToken::Identifier)) {
325  auto Type = parseType(Lexer.getTok().getString());
326  if (!Type)
327  return error("unknown type: ", Lexer.getTok());
328  Types.push_back(Type.getValue());
329  Parser.Lex();
330  if (!isNext(AsmToken::Comma))
331  break;
332  }
333  return false;
334  }
335 
336  void parseSingleInteger(bool IsNegative, OperandVector &Operands) {
337  auto &Int = Lexer.getTok();
338  int64_t Val = Int.getIntVal();
339  if (IsNegative)
340  Val = -Val;
341  Operands.push_back(make_unique<WebAssemblyOperand>(
342  WebAssemblyOperand::Integer, Int.getLoc(), Int.getEndLoc(),
343  WebAssemblyOperand::IntOp{Val}));
344  Parser.Lex();
345  }
346 
347  bool parseOperandStartingWithInteger(bool IsNegative, OperandVector &Operands,
348  StringRef InstName) {
349  parseSingleInteger(IsNegative, Operands);
350  // FIXME: there is probably a cleaner way to do this.
351  auto IsLoadStore = InstName.startswith("load") ||
352  InstName.startswith("store") ||
353  InstName.startswith("atomic");
354  if (IsLoadStore) {
355  // Parse load/store operands of the form: offset align
356  auto &Offset = Lexer.getTok();
357  if (Offset.is(AsmToken::Integer)) {
358  parseSingleInteger(false, Operands);
359  } else {
360  // Alignment not specified.
361  // FIXME: correctly derive a default from the instruction.
362  // We can't just call WebAssembly::GetDefaultP2Align since we don't have
363  // an opcode until after the assembly matcher.
364  Operands.push_back(make_unique<WebAssemblyOperand>(
365  WebAssemblyOperand::Integer, Offset.getLoc(), Offset.getEndLoc(),
366  WebAssemblyOperand::IntOp{0}));
367  }
368  }
369  return false;
370  }
371 
372  void addBlockTypeOperand(OperandVector &Operands, SMLoc NameLoc,
374  Operands.push_back(make_unique<WebAssemblyOperand>(
375  WebAssemblyOperand::Integer, NameLoc, NameLoc,
376  WebAssemblyOperand::IntOp{static_cast<int64_t>(BT)}));
377  }
378 
379  bool ParseInstruction(ParseInstructionInfo & /*Info*/, StringRef Name,
380  SMLoc NameLoc, OperandVector &Operands) override {
381  // Note: Name does NOT point into the sourcecode, but to a local, so
382  // use NameLoc instead.
383  Name = StringRef(NameLoc.getPointer(), Name.size());
384 
385  // WebAssembly has instructions with / in them, which AsmLexer parses
386  // as seperate tokens, so if we find such tokens immediately adjacent (no
387  // whitespace), expand the name to include them:
388  for (;;) {
389  auto &Sep = Lexer.getTok();
390  if (Sep.getLoc().getPointer() != Name.end() ||
391  Sep.getKind() != AsmToken::Slash)
392  break;
393  // Extend name with /
394  Name = StringRef(Name.begin(), Name.size() + Sep.getString().size());
395  Parser.Lex();
396  // We must now find another identifier, or error.
397  auto &Id = Lexer.getTok();
398  if (Id.getKind() != AsmToken::Identifier ||
399  Id.getLoc().getPointer() != Name.end())
400  return error("Incomplete instruction name: ", Id);
401  Name = StringRef(Name.begin(), Name.size() + Id.getString().size());
402  Parser.Lex();
403  }
404 
405  // Now construct the name as first operand.
406  Operands.push_back(make_unique<WebAssemblyOperand>(
407  WebAssemblyOperand::Token, NameLoc, SMLoc::getFromPointer(Name.end()),
408  WebAssemblyOperand::TokOp{Name}));
409  auto NamePair = Name.split('.');
410  // If no '.', there is no type prefix.
411  auto BaseName = NamePair.second.empty() ? NamePair.first : NamePair.second;
412 
413  // If this instruction is part of a control flow structure, ensure
414  // proper nesting.
415  bool ExpectBlockType = false;
416  if (BaseName == "block") {
417  push(Block);
418  ExpectBlockType = true;
419  } else if (BaseName == "loop") {
420  push(Loop);
421  ExpectBlockType = true;
422  } else if (BaseName == "try") {
423  push(Try);
424  ExpectBlockType = true;
425  } else if (BaseName == "if") {
426  push(If);
427  ExpectBlockType = true;
428  } else if (BaseName == "else") {
429  if (pop(BaseName, If))
430  return true;
431  push(Else);
432  } else if (BaseName == "catch") {
433  if (pop(BaseName, Try))
434  return true;
435  push(Try);
436  } else if (BaseName == "catch_all") {
437  if (pop(BaseName, Try))
438  return true;
439  push(Try);
440  } else if (BaseName == "end_if") {
441  if (pop(BaseName, If, Else))
442  return true;
443  } else if (BaseName == "end_try") {
444  if (pop(BaseName, Try))
445  return true;
446  } else if (BaseName == "end_loop") {
447  if (pop(BaseName, Loop))
448  return true;
449  } else if (BaseName == "end_block") {
450  if (pop(BaseName, Block))
451  return true;
452  } else if (BaseName == "end_function") {
453  CurrentState = EndFunction;
454  if (pop(BaseName, Function) || ensureEmptyNestingStack())
455  return true;
456  }
457 
458  while (Lexer.isNot(AsmToken::EndOfStatement)) {
459  auto &Tok = Lexer.getTok();
460  switch (Tok.getKind()) {
461  case AsmToken::Identifier: {
462  auto &Id = Lexer.getTok();
463  if (ExpectBlockType) {
464  // Assume this identifier is a block_type.
465  auto BT = parseBlockType(Id.getString());
467  return error("Unknown block type: ", Id);
468  addBlockTypeOperand(Operands, NameLoc, BT);
469  Parser.Lex();
470  } else {
471  // Assume this identifier is a label.
472  const MCExpr *Val;
473  SMLoc End;
474  if (Parser.parsePrimaryExpr(Val, End))
475  return error("Cannot parse symbol: ", Lexer.getTok());
476  Operands.push_back(make_unique<WebAssemblyOperand>(
477  WebAssemblyOperand::Symbol, Id.getLoc(), Id.getEndLoc(),
478  WebAssemblyOperand::SymOp{Val}));
479  }
480  break;
481  }
482  case AsmToken::Minus:
483  Parser.Lex();
484  if (Lexer.isNot(AsmToken::Integer))
485  return error("Expected integer instead got: ", Lexer.getTok());
486  if (parseOperandStartingWithInteger(true, Operands, BaseName))
487  return true;
488  break;
489  case AsmToken::Integer:
490  if (parseOperandStartingWithInteger(false, Operands, BaseName))
491  return true;
492  break;
493  case AsmToken::Real: {
494  double Val;
495  if (Tok.getString().getAsDouble(Val, false))
496  return error("Cannot parse real: ", Tok);
497  Operands.push_back(make_unique<WebAssemblyOperand>(
499  WebAssemblyOperand::FltOp{Val}));
500  Parser.Lex();
501  break;
502  }
503  case AsmToken::LCurly: {
504  Parser.Lex();
505  auto Op = make_unique<WebAssemblyOperand>(
506  WebAssemblyOperand::BrList, Tok.getLoc(), Tok.getEndLoc());
507  if (!Lexer.is(AsmToken::RCurly))
508  for (;;) {
509  Op->BrL.List.push_back(Lexer.getTok().getIntVal());
510  expect(AsmToken::Integer, "integer");
511  if (!isNext(AsmToken::Comma))
512  break;
513  }
514  expect(AsmToken::RCurly, "}");
515  Operands.push_back(std::move(Op));
516  break;
517  }
518  default:
519  return error("Unexpected token in operand: ", Tok);
520  }
521  if (Lexer.isNot(AsmToken::EndOfStatement)) {
522  if (expect(AsmToken::Comma, ","))
523  return true;
524  }
525  }
526  if (ExpectBlockType && Operands.size() == 1) {
527  // Support blocks with no operands as default to void.
528  addBlockTypeOperand(Operands, NameLoc, WebAssembly::ExprType::Void);
529  }
530  Parser.Lex();
531  return false;
532  }
533 
534  void onLabelParsed(MCSymbol *Symbol) override {
535  LastLabel = Symbol;
536  CurrentState = Label;
537  }
538 
539  bool parseSignature(wasm::WasmSignature *Signature) {
540  if (expect(AsmToken::LParen, "("))
541  return true;
542  if (parseRegTypeList(Signature->Params))
543  return true;
544  if (expect(AsmToken::RParen, ")"))
545  return true;
546  if (expect(AsmToken::MinusGreater, "->"))
547  return true;
548  if (expect(AsmToken::LParen, "("))
549  return true;
550  if (parseRegTypeList(Signature->Returns))
551  return true;
552  if (expect(AsmToken::RParen, ")"))
553  return true;
554  return false;
555  }
556 
557  bool CheckDataSection() {
558  if (CurrentState != DataSection) {
559  auto WS = cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
560  if (WS && WS->getKind().isText())
561  return error("data directive must occur in a data segment: ",
562  Lexer.getTok());
563  }
564  CurrentState = DataSection;
565  return false;
566  }
567 
568  // This function processes wasm-specific directives streamed to
569  // WebAssemblyTargetStreamer, all others go to the generic parser
570  // (see WasmAsmParser).
571  bool ParseDirective(AsmToken DirectiveID) override {
572  // This function has a really weird return value behavior that is different
573  // from all the other parsing functions:
574  // - return true && no tokens consumed -> don't know this directive / let
575  // the generic parser handle it.
576  // - return true && tokens consumed -> a parsing error occurred.
577  // - return false -> processed this directive successfully.
578  assert(DirectiveID.getKind() == AsmToken::Identifier);
579  auto &Out = getStreamer();
580  auto &TOut =
581  reinterpret_cast<WebAssemblyTargetStreamer &>(*Out.getTargetStreamer());
582  auto &Ctx = Out.getContext();
583 
584  // TODO: any time we return an error, at least one token must have been
585  // consumed, otherwise this will not signal an error to the caller.
586  if (DirectiveID.getString() == ".globaltype") {
587  auto SymName = expectIdent();
588  if (SymName.empty())
589  return true;
590  if (expect(AsmToken::Comma, ","))
591  return true;
592  auto TypeTok = Lexer.getTok();
593  auto TypeName = expectIdent();
594  if (TypeName.empty())
595  return true;
596  auto Type = parseType(TypeName);
597  if (!Type)
598  return error("Unknown type in .globaltype directive: ", TypeTok);
599  // Now set this symbol with the correct type.
600  auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
601  WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
602  WasmSym->setGlobalType(
603  wasm::WasmGlobalType{uint8_t(Type.getValue()), true});
604  // And emit the directive again.
605  TOut.emitGlobalType(WasmSym);
606  return expect(AsmToken::EndOfStatement, "EOL");
607  }
608 
609  if (DirectiveID.getString() == ".functype") {
610  // This code has to send things to the streamer similar to
611  // WebAssemblyAsmPrinter::EmitFunctionBodyStart.
612  // TODO: would be good to factor this into a common function, but the
613  // assembler and backend really don't share any common code, and this code
614  // parses the locals seperately.
615  auto SymName = expectIdent();
616  if (SymName.empty())
617  return true;
618  auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
619  if (CurrentState == Label && WasmSym == LastLabel) {
620  // This .functype indicates a start of a function.
621  if (ensureEmptyNestingStack())
622  return true;
623  CurrentState = FunctionStart;
624  LastFunctionLabel = LastLabel;
625  push(Function);
626  }
627  auto Signature = make_unique<wasm::WasmSignature>();
628  if (parseSignature(Signature.get()))
629  return true;
630  WasmSym->setSignature(Signature.get());
631  addSignature(std::move(Signature));
632  WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
633  TOut.emitFunctionType(WasmSym);
634  // TODO: backend also calls TOut.emitIndIdx, but that is not implemented.
635  return expect(AsmToken::EndOfStatement, "EOL");
636  }
637 
638  if (DirectiveID.getString() == ".eventtype") {
639  auto SymName = expectIdent();
640  if (SymName.empty())
641  return true;
642  auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
643  auto Signature = make_unique<wasm::WasmSignature>();
644  if (parseRegTypeList(Signature->Params))
645  return true;
646  WasmSym->setSignature(Signature.get());
647  addSignature(std::move(Signature));
648  WasmSym->setType(wasm::WASM_SYMBOL_TYPE_EVENT);
649  TOut.emitEventType(WasmSym);
650  // TODO: backend also calls TOut.emitIndIdx, but that is not implemented.
651  return expect(AsmToken::EndOfStatement, "EOL");
652  }
653 
654  if (DirectiveID.getString() == ".local") {
655  if (CurrentState != FunctionStart)
656  return error(".local directive should follow the start of a function",
657  Lexer.getTok());
659  if (parseRegTypeList(Locals))
660  return true;
661  TOut.emitLocal(Locals);
662  CurrentState = FunctionLocals;
663  return expect(AsmToken::EndOfStatement, "EOL");
664  }
665 
666  if (DirectiveID.getString() == ".int8") {
667  if (CheckDataSection()) return true;
668  int64_t V;
669  if (Parser.parseAbsoluteExpression(V))
670  return error("Cannot parse int8 constant: ", Lexer.getTok());
671  // TODO: error if value doesn't fit?
672  Out.EmitIntValue(static_cast<uint64_t>(V), 1);
673  return expect(AsmToken::EndOfStatement, "EOL");
674  }
675 
676  if (DirectiveID.getString() == ".asciz") {
677  if (CheckDataSection()) return true;
678  std::string S;
679  if (Parser.parseEscapedString(S))
680  return error("Cannot parse string constant: ", Lexer.getTok());
681  Out.EmitBytes(StringRef(S.c_str(), S.length() + 1));
682  return expect(AsmToken::EndOfStatement, "EOL");
683  }
684 
685  return true; // We didn't process this directive.
686  }
687 
688  bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned & /*Opcode*/,
689  OperandVector &Operands, MCStreamer &Out,
690  uint64_t &ErrorInfo,
691  bool MatchingInlineAsm) override {
692  MCInst Inst;
693  unsigned MatchResult =
694  MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
695  switch (MatchResult) {
696  case Match_Success: {
697  if (CurrentState == FunctionStart) {
698  // This is the first instruction in a function, but we haven't seen
699  // a .local directive yet. The streamer requires locals to be encoded
700  // as a prelude to the instructions, so emit an empty list of locals
701  // here.
702  auto &TOut = reinterpret_cast<WebAssemblyTargetStreamer &>(
703  *Out.getTargetStreamer());
705  }
706  Out.EmitInstruction(Inst, getSTI());
707  if (CurrentState == EndFunction) {
708  onEndOfFunction();
709  } else {
710  CurrentState = Instructions;
711  }
712  return false;
713  }
714  case Match_MissingFeature:
715  return Parser.Error(
716  IDLoc, "instruction requires a WASM feature not currently enabled");
717  case Match_MnemonicFail:
718  return Parser.Error(IDLoc, "invalid instruction");
719  case Match_NearMisses:
720  return Parser.Error(IDLoc, "ambiguous instruction");
721  case Match_InvalidTiedOperand:
722  case Match_InvalidOperand: {
723  SMLoc ErrorLoc = IDLoc;
724  if (ErrorInfo != ~0ULL) {
725  if (ErrorInfo >= Operands.size())
726  return Parser.Error(IDLoc, "too few operands for instruction");
727  ErrorLoc = Operands[ErrorInfo]->getStartLoc();
728  if (ErrorLoc == SMLoc())
729  ErrorLoc = IDLoc;
730  }
731  return Parser.Error(ErrorLoc, "invalid operand for instruction");
732  }
733  }
734  llvm_unreachable("Implement any new match types added!");
735  }
736 
737  void doBeforeLabelEmit(MCSymbol *Symbol) override {
738  // Start a new section for the next function automatically, since our
739  // object writer expects each function to have its own section. This way
740  // The user can't forget this "convention".
741  auto SymName = Symbol->getName();
742  if (SymName.startswith(".L"))
743  return; // Local Symbol.
744  auto SecName = ".text." + SymName;
745  auto WS = getContext().getWasmSection(SecName, SectionKind::getText());
746  getStreamer().SwitchSection(WS);
747  }
748 
749  void onEndOfFunction() {
750  // Automatically output a .size directive, so it becomes optional for the
751  // user.
752  if (!LastFunctionLabel) return;
753  auto TempSym = getContext().createLinkerPrivateTempSymbol();
754  getStreamer().EmitLabel(TempSym);
755  auto Start = MCSymbolRefExpr::create(LastFunctionLabel, getContext());
756  auto End = MCSymbolRefExpr::create(TempSym, getContext());
757  auto Expr =
758  MCBinaryExpr::create(MCBinaryExpr::Sub, End, Start, getContext());
759  getStreamer().emitELFSize(LastFunctionLabel, Expr);
760  }
761 
762  void onEndOfFile() override { ensureEmptyNestingStack(); }
763 };
764 } // end anonymous namespace
765 
766 // Force static initialization.
770 }
771 
772 #define GET_REGISTER_MATCHER
773 #define GET_MATCHER_IMPLEMENTATION
774 #include "WebAssemblyGenAsmMatcher.inc"
static bool isReg(const MCInst &MI, unsigned OpNo)
const AsmToken & getTok() const
Get the current (last) lexed token.
Definition: MCAsmLexer.h:100
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
StringRef getString() const
Get the string for the current token, this includes all characters (for example, the quotes on string...
Definition: MCAsmMacro.h:110
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:321
This class represents lattice values for constants.
Definition: AllocatorList.h:23
bool is(AsmToken::TokenKind K) const
Check if the current token has kind K.
Definition: MCAsmLexer.h:135
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
Generic assembler parser interface, for use by target specific assembly parsers.
Definition: MCAsmParser.h:109
static MCOperand createExpr(const MCExpr *Val)
Definition: MCInst.h:136
MCTargetAsmParser - Generic interface to target specific assembly parsers.
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:256
virtual const AsmToken & Lex()=0
Get the next AsmToken in the stream, possibly handling file inclusion first.
unsigned second
#define error(X)
F(f)
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end...
virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI)
Emit the given Instruction into the current section.
Definition: MCStreamer.cpp:960
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:67
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
This file registers the WebAssembly target.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
const FeatureBitset & getFeatureBits() const
Generic assembler lexer interface, for use by target specific assembly lexers.
Definition: MCAsmLexer.h:39
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:41
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
SmallVector< ValType, 1 > Returns
Definition: Wasm.h:336
LLVM_NODISCARD R Default(T Value)
Definition: StringSwitch.h:181
Target independent representation for an assembler token.
Definition: MCAsmMacro.h:21
static bool isMem(const MachineInstr &MI, unsigned Op)
Definition: X86InstrInfo.h:122
MCParsedAsmOperand - This abstract class represents a source-level assembly instruction operand...
SmallVector< ValType, 4 > Params
Definition: Wasm.h:337
std::pair< StringRef, StringRef > getToken(StringRef Source, StringRef Delimiters=" \\\)
getToken - This function extracts one token from source, ignoring any leading characters that appear ...
RegisterMCAsmParser - Helper template for registering a target specific assembly parser, for use in the target machine initialization function.
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:130
SMLoc getLoc() const
Definition: MCAsmLexer.cpp:27
virtual bool parseEscapedString(std::string &Data)=0
Parse the current token as a string which may include escaped characters and return the string conten...
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:158
static const MCBinaryExpr * create(Opcode Op, const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition: MCExpr.cpp:152
WebAssembly-specific streamer interface, to implement support WebAssembly-specific assembly directive...
const char * getPointer() const
Definition: SMLoc.h:34
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:42
Streaming machine code generation interface.
Definition: MCStreamer.h:188
MCTargetStreamer * getTargetStreamer()
Definition: MCStreamer.h:257
SMLoc getEndLoc() const
Definition: MCAsmLexer.cpp:31
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
This file provides WebAssembly-specific target descriptions.
virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc)=0
Parse a primary expression.
Interface to description of machine instruction set.
Definition: MCInstrInfo.h:23
virtual MCAsmLexer & getLexer()=0
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
int64_t getIntVal() const
Definition: MCAsmMacro.h:115
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
bool Error(SMLoc L, const Twine &Msg, SMRange Range=None)
Return an error at the location L, with the message Msg.
Definition: MCAsmParser.cpp:87
size_t size() const
Definition: SmallVector.h:52
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned first
This file declares WebAssembly-specific target streamer classes.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:696
bool getAsDouble(double &Result, bool AllowInexact=true) const
Parse the current string as an IEEE double-precision floating point value.
Definition: StringRef.cpp:583
ExprType
This is used to indicate block signatures.
static MCOperand createFPImm(double Val)
Definition: MCInst.h:129
void LLVMInitializeWebAssemblyAsmParser()
static unsigned getReg(const void *D, unsigned RC, unsigned RegNo)
Base class for user error types.
Definition: Error.h:344
iterator begin() const
Definition: StringRef.h:101
static SMLoc getFromPointer(const char *Ptr)
Definition: SMLoc.h:36
BitTracker BT
Definition: BitTracker.cpp:73
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:467
const NodeList & List
Definition: RDFGraph.cpp:201
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
Generic base class for all target subtargets.
virtual bool parseAbsoluteExpression(int64_t &Res)=0
Parse an expression which must evaluate to an absolute value.
bool isNot(AsmToken::TokenKind K) const
Check if the current token has kind K.
Definition: MCAsmLexer.h:138
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:203
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
virtual void emitLocal(ArrayRef< wasm::ValType > Types)=0
.local
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
Subtraction.
Definition: MCExpr.h:439
void addOperand(const MCOperand &Op)
Definition: MCInst.h:183
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
Target & getTheWebAssemblyTarget32()
Type * parseType(StringRef Asm, SMDiagnostic &Err, const Module &M, const SlotMapping *Slots=nullptr)
Parse a type in the given string.
Definition: Parser.cpp:159
Represents a location in source code.
Definition: SMLoc.h:23
Target & getTheWebAssemblyTarget64()
iterator end() const
Definition: StringRef.h:103
static MCOperand createImm(int64_t Val)
Definition: MCInst.h:122
TokenKind getKind() const
Definition: MCAsmMacro.h:81
static SectionKind getText()
Definition: SectionKind.h:179