[llvm] r328028 - [WebAssembly] Added initial AsmParser implementation.

Derek Schuff via llvm-commits llvm-commits at lists.llvm.org
Tue Mar 20 13:06:35 PDT 2018


Author: dschuff
Date: Tue Mar 20 13:06:35 2018
New Revision: 328028

URL: http://llvm.org/viewvc/llvm-project?rev=328028&view=rev
Log:
[WebAssembly] Added initial AsmParser implementation.

It uses the MC framework and the tablegen matcher to do the
heavy lifting. Can handle both explicit and implicit locals
(-disable-wasm-explicit-locals). Comes with a small regression
test.

This is a first basic implementation that can parse most llvm .s
output and round-trips most instructions succesfully, but in order
to keep the commit small, does not address all issues.

There are a fair number of mismatches between what MC / assembly
matcher think a "CPU" should look like and what WASM provides,
some already have workarounds in this commit (e.g. the way it
deals with register operands) and some that require further work.
Some of that further work may involve changing what the
Disassembler outputs (and what s2wasm parses), so are probably
best left to followups.

Some known things missing:
- Many directives are ignored and not emitted.
- Vararg calls are parsed but extra args not emitted.
- Loop signatures are likely incorrect.
- $drop= is not emitted.
- Disassembler does not output SIMD types correctly, so assembler
  can't test them.

Patch by Wouter van Oortmerssen

Differential Revision: https://reviews.llvm.org/D44329

Added:
    llvm/trunk/lib/Target/WebAssembly/AsmParser/
    llvm/trunk/lib/Target/WebAssembly/AsmParser/CMakeLists.txt
    llvm/trunk/lib/Target/WebAssembly/AsmParser/LLVMBuild.txt
      - copied, changed from r328024, llvm/trunk/lib/Target/WebAssembly/LLVMBuild.txt
    llvm/trunk/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmParser.cpp
    llvm/trunk/test/MC/WebAssembly/basic-assembly.s
Modified:
    llvm/trunk/lib/MC/MCExpr.cpp
    llvm/trunk/lib/Target/WebAssembly/CMakeLists.txt
    llvm/trunk/lib/Target/WebAssembly/InstPrinter/WebAssemblyInstPrinter.cpp
    llvm/trunk/lib/Target/WebAssembly/LLVMBuild.txt
    llvm/trunk/lib/Target/WebAssembly/WebAssembly.td
    llvm/trunk/lib/Target/WebAssembly/WebAssemblyRegisterInfo.td

Modified: llvm/trunk/lib/MC/MCExpr.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/MC/MCExpr.cpp?rev=328028&r1=328027&r2=328028&view=diff
==============================================================================
--- llvm/trunk/lib/MC/MCExpr.cpp (original)
+++ llvm/trunk/lib/MC/MCExpr.cpp Tue Mar 20 13:06:35 2018
@@ -399,6 +399,8 @@ MCSymbolRefExpr::getVariantKindForName(S
     .Case("lo8", VK_AVR_LO8)
     .Case("hi8", VK_AVR_HI8)
     .Case("hlo8", VK_AVR_HLO8)
+    .Case("function", VK_WebAssembly_FUNCTION)
+    .Case("typeindex", VK_WebAssembly_TYPEINDEX)
     .Case("gotpcrel32 at lo", VK_AMDGPU_GOTPCREL32_LO)
     .Case("gotpcrel32 at hi", VK_AMDGPU_GOTPCREL32_HI)
     .Case("rel32 at lo", VK_AMDGPU_REL32_LO)

Added: llvm/trunk/lib/Target/WebAssembly/AsmParser/CMakeLists.txt
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Target/WebAssembly/AsmParser/CMakeLists.txt?rev=328028&view=auto
==============================================================================
--- llvm/trunk/lib/Target/WebAssembly/AsmParser/CMakeLists.txt (added)
+++ llvm/trunk/lib/Target/WebAssembly/AsmParser/CMakeLists.txt Tue Mar 20 13:06:35 2018
@@ -0,0 +1,3 @@
+add_llvm_library(LLVMWebAssemblyAsmParser
+  WebAssemblyAsmParser.cpp
+  )

Copied: llvm/trunk/lib/Target/WebAssembly/AsmParser/LLVMBuild.txt (from r328024, llvm/trunk/lib/Target/WebAssembly/LLVMBuild.txt)
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Target/WebAssembly/AsmParser/LLVMBuild.txt?p2=llvm/trunk/lib/Target/WebAssembly/AsmParser/LLVMBuild.txt&p1=llvm/trunk/lib/Target/WebAssembly/LLVMBuild.txt&r1=328024&r2=328028&rev=328028&view=diff
==============================================================================
--- llvm/trunk/lib/Target/WebAssembly/LLVMBuild.txt (original)
+++ llvm/trunk/lib/Target/WebAssembly/AsmParser/LLVMBuild.txt Tue Mar 20 13:06:35 2018
@@ -1,4 +1,4 @@
-;===- ./lib/Target/WebAssembly/LLVMBuild.txt -------------------*- Conf -*--===;
+;===-- ./lib/Target/WebAssembly/Disassembler/LLVMBuild.txt -----*- Conf -*--===;
 ;
 ;                     The LLVM Compiler Infrastructure
 ;
@@ -15,19 +15,9 @@
 ;
 ;===------------------------------------------------------------------------===;
 
-[common]
-subdirectories = Disassembler InstPrinter MCTargetDesc TargetInfo
-
 [component_0]
-type = TargetGroup
-name = WebAssembly
-parent = Target
-has_asmprinter = 1
-has_disassembler = 1
-
-[component_1]
 type = Library
-name = WebAssemblyCodeGen
+name = WebAssemblyAsmParser
 parent = WebAssembly
-required_libraries = Analysis AsmPrinter CodeGen Core MC Scalar SelectionDAG Support Target TransformUtils WebAssemblyAsmPrinter WebAssemblyDesc WebAssemblyInfo
+required_libraries = MC MCParser WebAssemblyInfo Support
 add_to_library_groups = WebAssembly

Added: llvm/trunk/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmParser.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmParser.cpp?rev=328028&view=auto
==============================================================================
--- llvm/trunk/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmParser.cpp (added)
+++ llvm/trunk/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmParser.cpp Tue Mar 20 13:06:35 2018
@@ -0,0 +1,561 @@
+//==- WebAssemblyAsmParser.cpp - Assembler for WebAssembly -*- C++ -*-==//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief This file is part of the WebAssembly Assembler.
+///
+/// It contains code to translate a parsed .s file into MCInsts.
+///
+//===----------------------------------------------------------------------===//
+
+#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
+#include "MCTargetDesc/WebAssemblyTargetStreamer.h"
+#include "WebAssembly.h"
+#include "llvm/MC/MCContext.h"
+#include "llvm/MC/MCParser/MCTargetAsmParser.h"
+#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
+#include "llvm/MC/MCInst.h"
+#include "llvm/MC/MCInstrInfo.h"
+#include "llvm/MC/MCSubtargetInfo.h"
+#include "llvm/MC/MCSymbol.h"
+#include "llvm/MC/MCStreamer.h"
+#include "llvm/Support/Endian.h"
+#include "llvm/Support/TargetRegistry.h"
+
+using namespace llvm;
+
+#define DEBUG_TYPE "wasm-asm-parser"
+
+namespace {
+
+// We store register types as SimpleValueType to retain SIMD layout
+// information, but must also be able to supply them as the (unnamed)
+// register enum from WebAssemblyRegisterInfo.td/.inc.
+static unsigned MVTToWasmReg(MVT::SimpleValueType Type) {
+  switch(Type) {
+    case MVT::i32: return WebAssembly::I32_0;
+    case MVT::i64: return WebAssembly::I64_0;
+    case MVT::f32: return WebAssembly::F32_0;
+    case MVT::f64: return WebAssembly::F64_0;
+    case MVT::v16i8: return WebAssembly::V128_0;
+    case MVT::v8i16: return WebAssembly::V128_0;
+    case MVT::v4i32: return WebAssembly::V128_0;
+    case MVT::v4f32: return WebAssembly::V128_0;
+    default: return MVT::INVALID_SIMPLE_VALUE_TYPE;
+  }
+}
+
+/// WebAssemblyOperand - Instances of this class represent the operands in a
+/// parsed WASM machine instruction.
+struct WebAssemblyOperand : public MCParsedAsmOperand {
+  enum KindTy { Token, Local, Stack, Integer, Float, Symbol } Kind;
+
+  SMLoc StartLoc, EndLoc;
+
+  struct TokOp {
+    StringRef Tok;
+  };
+
+  struct RegOp {
+    // This is a (virtual) local or stack register represented as 0..
+    unsigned RegNo;
+    // In most targets, the register number also encodes the type, but for
+    // wasm we have to track that seperately since we have an unbounded
+    // number of registers.
+    // This has the unfortunate side effect that we supply a different value
+    // to the table-gen matcher at different times in the process (when it
+    // calls getReg() or addRegOperands().
+    // TODO: While this works, it feels brittle. and would be nice to clean up.
+    MVT::SimpleValueType Type;
+  };
+
+  struct IntOp {
+    int64_t Val;
+  };
+
+  struct FltOp {
+    double Val;
+  };
+
+  struct SymOp {
+    const MCExpr *Exp;
+  };
+
+  union {
+    struct TokOp Tok;
+    struct RegOp Reg;
+    struct IntOp Int;
+    struct FltOp Flt;
+    struct SymOp Sym;
+  };
+
+  WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, TokOp T)
+    : Kind(K), StartLoc(Start), EndLoc(End), Tok(T) {}
+  WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, RegOp R)
+    : Kind(K), StartLoc(Start), EndLoc(End), Reg(R) {}
+  WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, IntOp I)
+    : Kind(K), StartLoc(Start), EndLoc(End), Int(I) {}
+  WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, FltOp F)
+    : Kind(K), StartLoc(Start), EndLoc(End), Flt(F) {}
+  WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, SymOp S)
+    : Kind(K), StartLoc(Start), EndLoc(End), Sym(S) {}
+
+  bool isToken() const override { return Kind == Token; }
+  bool isImm() const override { return Kind == Integer ||
+                                       Kind == Float ||
+                                       Kind == Symbol; }
+  bool isReg() const override { return Kind == Local || Kind == Stack; }
+  bool isMem() const override { return false; }
+
+  unsigned getReg() const override {
+    assert(isReg());
+    // This is called from the tablegen matcher (MatchInstructionImpl)
+    // where it expects to match the type of register, see RegOp above.
+    return MVTToWasmReg(Reg.Type);
+  }
+
+  StringRef getToken() const {
+    assert(isToken());
+    return Tok.Tok;
+  }
+
+  SMLoc getStartLoc() const override { return StartLoc; }
+  SMLoc getEndLoc() const override { return EndLoc; }
+
+  void addRegOperands(MCInst &Inst, unsigned N) const {
+    assert(N == 1 && "Invalid number of operands!");
+    assert(isReg() && "Not a register operand!");
+    // This is called from the tablegen matcher (MatchInstructionImpl)
+    // where it expects to output the actual register index, see RegOp above.
+    unsigned R = Reg.RegNo;
+    if (Kind == Stack) {
+      // A stack register is represented as a large negative number.
+      // See WebAssemblyRegNumbering::runOnMachineFunction and
+      // getWARegStackId for why this | is needed.
+      R |= INT32_MIN;
+    }
+    Inst.addOperand(MCOperand::createReg(R));
+  }
+
+  void addImmOperands(MCInst &Inst, unsigned N) const {
+    assert(N == 1 && "Invalid number of operands!");
+    if (Kind == Integer)
+      Inst.addOperand(MCOperand::createImm(Int.Val));
+    else if (Kind == Float)
+      Inst.addOperand(MCOperand::createFPImm(Flt.Val));
+    else if (Kind == Symbol)
+      Inst.addOperand(MCOperand::createExpr(Sym.Exp));
+    else
+      llvm_unreachable("Should be immediate or symbol!");
+  }
+
+  void print(raw_ostream &OS) const override {
+    switch (Kind) {
+    case Token:
+      OS << "Tok:" << Tok.Tok;
+      break;
+    case Local:
+      OS << "Loc:" << Reg.RegNo << ":" << static_cast<int>(Reg.Type);
+      break;
+    case Stack:
+      OS << "Stk:" << Reg.RegNo << ":" << static_cast<int>(Reg.Type);
+      break;
+    case Integer:
+      OS << "Int:" << Int.Val;
+      break;
+    case Float:
+      OS << "Flt:" << Flt.Val;
+      break;
+    case Symbol:
+      OS << "Sym:" << Sym.Exp;
+      break;
+    }
+  }
+};
+
+class WebAssemblyAsmParser final : public MCTargetAsmParser {
+  MCAsmParser &Parser;
+  MCAsmLexer &Lexer;
+  // These are for the current function being parsed:
+  // These are vectors since register assignments are so far non-sparse.
+  // Replace by map if necessary.
+  std::vector<MVT::SimpleValueType> LocalTypes;
+  std::vector<MVT::SimpleValueType> StackTypes;
+  MCSymbol *LastLabel;
+
+public:
+  WebAssemblyAsmParser(const MCSubtargetInfo &sti, MCAsmParser &Parser,
+                       const MCInstrInfo &mii, const MCTargetOptions &Options)
+      : MCTargetAsmParser(Options, sti, mii), Parser(Parser),
+        Lexer(Parser.getLexer()), LastLabel(nullptr) {
+  }
+
+#define GET_ASSEMBLER_HEADER
+#include "WebAssemblyGenAsmMatcher.inc"
+
+  // TODO: This is required to be implemented, but appears unused.
+  bool ParseRegister(unsigned &/*RegNo*/, SMLoc &/*StartLoc*/,
+                     SMLoc &/*EndLoc*/) override {
+    llvm_unreachable("ParseRegister is not implemented.");
+  }
+
+  bool Error(const StringRef &msg, const AsmToken &tok) {
+    return Parser.Error(tok.getLoc(), msg + tok.getString());
+  }
+
+  bool IsNext(AsmToken::TokenKind Kind) {
+    auto ok = Lexer.is(Kind);
+    if (ok) Parser.Lex();
+    return ok;
+  }
+
+  bool Expect(AsmToken::TokenKind Kind, const char *KindName) {
+    if (!IsNext(Kind))
+      return Error(std::string("Expected ") + KindName + ", instead got: ",
+                   Lexer.getTok());
+    return false;
+  }
+
+  MVT::SimpleValueType ParseRegType(const StringRef &RegType) {
+    // Derive type from .param .local decls, or the instruction itself.
+    return StringSwitch<MVT::SimpleValueType>(RegType)
+        .Case("i32", MVT::i32)
+        .Case("i64", MVT::i64)
+        .Case("f32", MVT::f32)
+        .Case("f64", MVT::f64)
+        .Case("i8x16", MVT::v16i8)
+        .Case("i16x8", MVT::v8i16)
+        .Case("i32x4", MVT::v4i32)
+        .Case("f32x4", MVT::v4f32)
+        .Default(MVT::INVALID_SIMPLE_VALUE_TYPE);
+  }
+
+  MVT::SimpleValueType &GetType(
+      std::vector<MVT::SimpleValueType> &Types, size_t i) {
+    Types.resize(std::max(i + 1, Types.size()), MVT::INVALID_SIMPLE_VALUE_TYPE);
+    return Types[i];
+  }
+
+  bool ParseReg(OperandVector &Operands, StringRef TypePrefix) {
+    if (Lexer.is(AsmToken::Integer)) {
+      auto &Local = Lexer.getTok();
+      // This is a reference to a local, turn it into a virtual register.
+      auto LocalNo = static_cast<unsigned>(Local.getIntVal());
+      Operands.push_back(make_unique<WebAssemblyOperand>(
+                           WebAssemblyOperand::Local, Local.getLoc(),
+                           Local.getEndLoc(),
+                           WebAssemblyOperand::RegOp{LocalNo,
+                               GetType(LocalTypes, LocalNo)}));
+      Parser.Lex();
+    } else if (Lexer.is(AsmToken::Identifier)) {
+      auto &StackRegTok = Lexer.getTok();
+      // These are push/pop/drop pseudo stack registers, which we turn
+      // into virtual registers also. The stackify pass will later turn them
+      // back into implicit stack references if possible.
+      auto StackReg = StackRegTok.getString();
+      auto StackOp = StackReg.take_while([](char c) { return isalpha(c); });
+      auto Reg = StackReg.drop_front(StackOp.size());
+      unsigned long long ParsedRegNo = 0;
+      if (!Reg.empty() && getAsUnsignedInteger(Reg, 10, ParsedRegNo))
+        return Error("Cannot parse stack register index: ", StackRegTok);
+      unsigned RegNo = static_cast<unsigned>(ParsedRegNo);
+      if (StackOp == "push") {
+        // This defines a result, record register type.
+        auto RegType = ParseRegType(TypePrefix);
+        GetType(StackTypes, RegNo) = RegType;
+        Operands.push_back(make_unique<WebAssemblyOperand>(
+                             WebAssemblyOperand::Stack,
+                             StackRegTok.getLoc(),
+                             StackRegTok.getEndLoc(),
+                             WebAssemblyOperand::RegOp{RegNo, RegType}));
+      } else if (StackOp == "pop") {
+        // This uses a previously defined stack value.
+        auto RegType = GetType(StackTypes, RegNo);
+        Operands.push_back(make_unique<WebAssemblyOperand>(
+                             WebAssemblyOperand::Stack,
+                             StackRegTok.getLoc(),
+                             StackRegTok.getEndLoc(),
+                             WebAssemblyOperand::RegOp{RegNo, RegType}));
+      } else if (StackOp == "drop") {
+        // This operand will be dropped, since it is part of an instruction
+        // whose result is void.
+      } else {
+        return Error("Unknown stack register prefix: ", StackRegTok);
+      }
+      Parser.Lex();
+    } else {
+      return Error(
+            "Expected identifier/integer following $, instead got: ",
+            Lexer.getTok());
+    }
+    IsNext(AsmToken::Equal);
+    return false;
+  }
+
+  void ParseSingleInteger(bool IsNegative, OperandVector &Operands) {
+    auto &Int = Lexer.getTok();
+    int64_t Val = Int.getIntVal();
+    if (IsNegative) Val = -Val;
+    Operands.push_back(make_unique<WebAssemblyOperand>(
+                         WebAssemblyOperand::Integer, Int.getLoc(),
+                         Int.getEndLoc(), WebAssemblyOperand::IntOp{Val}));
+    Parser.Lex();
+  }
+
+  bool ParseOperandStartingWithInteger(bool IsNegative,
+                                       OperandVector &Operands,
+                                       StringRef InstType) {
+    ParseSingleInteger(IsNegative, Operands);
+    if (Lexer.is(AsmToken::LParen)) {
+      // Parse load/store operands of the form: offset($reg)align
+      auto &LParen = Lexer.getTok();
+      Operands.push_back(
+            make_unique<WebAssemblyOperand>(WebAssemblyOperand::Token,
+                                            LParen.getLoc(),
+                                            LParen.getEndLoc(),
+                                            WebAssemblyOperand::TokOp{
+                                              LParen.getString()}));
+      Parser.Lex();
+      if (Expect(AsmToken::Dollar, "register")) return true;
+      if (ParseReg(Operands, InstType)) return true;
+      auto &RParen = Lexer.getTok();
+      Operands.push_back(
+            make_unique<WebAssemblyOperand>(WebAssemblyOperand::Token,
+                                            RParen.getLoc(),
+                                            RParen.getEndLoc(),
+                                            WebAssemblyOperand::TokOp{
+                                              RParen.getString()}));
+      if (Expect(AsmToken::RParen, ")")) return true;
+      if (Lexer.is(AsmToken::Integer)) {
+        ParseSingleInteger(false, Operands);
+      } else {
+        // Alignment not specified.
+        // FIXME: correctly derive a default from the instruction.
+        Operands.push_back(make_unique<WebAssemblyOperand>(
+                             WebAssemblyOperand::Integer, RParen.getLoc(),
+                             RParen.getEndLoc(), WebAssemblyOperand::IntOp{0}));
+      }
+    }
+    return false;
+  }
+
+  bool ParseInstruction(ParseInstructionInfo &/*Info*/, StringRef Name,
+                        SMLoc NameLoc, OperandVector &Operands) override {
+    Operands.push_back(
+          make_unique<WebAssemblyOperand>(WebAssemblyOperand::Token, NameLoc,
+                                          SMLoc::getFromPointer(
+                                            NameLoc.getPointer() + Name.size()),
+                                          WebAssemblyOperand::TokOp{
+                                            StringRef(NameLoc.getPointer(),
+                                                    Name.size())}));
+    auto NamePair = Name.split('.');
+    // If no '.', there is no type prefix.
+    if (NamePair.second.empty()) std::swap(NamePair.first, NamePair.second);
+    while (Lexer.isNot(AsmToken::EndOfStatement)) {
+      auto &Tok = Lexer.getTok();
+      switch (Tok.getKind()) {
+      case AsmToken::Dollar: {
+        Parser.Lex();
+        if (ParseReg(Operands, NamePair.first)) return true;
+        break;
+      }
+      case AsmToken::Identifier: {
+        auto &Id = Lexer.getTok();
+        const MCExpr *Val;
+        SMLoc End;
+        if (Parser.parsePrimaryExpr(Val, End))
+          return Error("Cannot parse symbol: ", Lexer.getTok());
+        Operands.push_back(make_unique<WebAssemblyOperand>(
+                             WebAssemblyOperand::Symbol, Id.getLoc(),
+                             Id.getEndLoc(), WebAssemblyOperand::SymOp{Val}));
+        break;
+      }
+      case AsmToken::Minus:
+        Parser.Lex();
+        if (Lexer.isNot(AsmToken::Integer))
+          return Error("Expected integer instead got: ", Lexer.getTok());
+        if (ParseOperandStartingWithInteger(true, Operands, NamePair.first))
+          return true;
+        break;
+      case AsmToken::Integer:
+        if (ParseOperandStartingWithInteger(false, Operands, NamePair.first))
+          return true;
+        break;
+      case AsmToken::Real: {
+        double Val;
+        if (Tok.getString().getAsDouble(Val, false))
+          return Error("Cannot parse real: ", Tok);
+        Operands.push_back(make_unique<WebAssemblyOperand>(
+                             WebAssemblyOperand::Float, Tok.getLoc(),
+                             Tok.getEndLoc(), WebAssemblyOperand::FltOp{Val}));
+        Parser.Lex();
+        break;
+      }
+      default:
+        return Error("Unexpected token in operand: ", Tok);
+      }
+      if (Lexer.isNot(AsmToken::EndOfStatement)) {
+        if (Expect(AsmToken::Comma, ",")) return true;
+      }
+    }
+    Parser.Lex();
+    // Call instructions are vararg, but the tablegen matcher doesn't seem to
+    // support that, so for now we strip these extra operands.
+    // This is problematic if these arguments are not simple $pop stack
+    // registers, since e.g. a local register would get lost, so we check for
+    // this. This can be the case when using -disable-wasm-explicit-locals
+    // which currently s2wasm requires.
+    // TODO: Instead, we can move this code to MatchAndEmitInstruction below and
+    // actually generate get_local instructions on the fly.
+    // Or even better, improve the matcher to support vararg?
+    auto IsIndirect = NamePair.second == "call_indirect";
+    if (IsIndirect || NamePair.second == "call") {
+      // Figure out number of fixed operands from the instruction.
+      size_t CallOperands = 1;  // The name token.
+      if (!IsIndirect) CallOperands++;  // The function index.
+      if (!NamePair.first.empty()) CallOperands++;  // The result register.
+      if (Operands.size() > CallOperands) {
+        // Ensure operands we drop are all $pop.
+        for (size_t I = CallOperands; I < Operands.size(); I++) {
+          auto Operand =
+              reinterpret_cast<WebAssemblyOperand *>(Operands[I].get());
+          if (Operand->Kind != WebAssemblyOperand::Stack)
+            Parser.Error(NameLoc,
+              "Call instruction has non-stack arguments, if this code was "
+              "generated with -disable-wasm-explicit-locals please remove it");
+        }
+        // Drop unneeded operands.
+        Operands.resize(CallOperands);
+      }
+    }
+    // Block instructions require a signature index, but these are missing in
+    // assembly, so we add a dummy one explicitly (since we have no control
+    // over signature tables here, we assume these will be regenerated when
+    // the wasm module is generated).
+    if (NamePair.second == "block" || NamePair.second == "loop") {
+      Operands.push_back(make_unique<WebAssemblyOperand>(
+                           WebAssemblyOperand::Integer, NameLoc,
+                           NameLoc, WebAssemblyOperand::IntOp{-1}));
+    }
+    // These don't specify the type, which has to derived from the local index.
+    if (NamePair.second == "get_local" || NamePair.second == "tee_local") {
+      if (Operands.size() >= 3 && Operands[1]->isReg() &&
+          Operands[2]->isImm()) {
+        auto Op1 = reinterpret_cast<WebAssemblyOperand *>(Operands[1].get());
+        auto Op2 = reinterpret_cast<WebAssemblyOperand *>(Operands[2].get());
+        auto Type = GetType(LocalTypes, static_cast<size_t>(Op2->Int.Val));
+        Op1->Reg.Type = Type;
+        GetType(StackTypes, Op1->Reg.RegNo) = Type;
+      }
+    }
+    return false;
+  }
+
+  void onLabelParsed(MCSymbol *Symbol) override {
+    LastLabel = Symbol;
+  }
+
+  bool ParseDirective(AsmToken DirectiveID) override {
+    assert(DirectiveID.getKind() == AsmToken::Identifier);
+    auto &Out = getStreamer();
+    auto &TOut = reinterpret_cast<WebAssemblyTargetStreamer &>(
+                   *Out.getTargetStreamer());
+    // TODO: we're just parsing the subset of directives we're interested in,
+    // and ignoring ones we don't recognise. We should ideally verify
+    // all directives here.
+    if (DirectiveID.getString() == ".type") {
+      // This could be the start of a function, check if followed by
+      // "label, at function"
+      if (!(IsNext(AsmToken::Identifier) &&
+            IsNext(AsmToken::Comma) &&
+            IsNext(AsmToken::At) &&
+            Lexer.is(AsmToken::Identifier)))
+        return Error("Expected label, at type declaration, got: ", Lexer.getTok());
+      if (Lexer.getTok().getString() == "function") {
+        // Track locals from start of function.
+        LocalTypes.clear();
+        StackTypes.clear();
+      }
+      Parser.Lex();
+      //Out.EmitSymbolAttribute(??, MCSA_ELF_TypeFunction);
+    } else if (DirectiveID.getString() == ".param" ||
+               DirectiveID.getString() == ".local") {
+      // Track the number of locals, needed for correct virtual register
+      // assignment elsewhere.
+      // Also output a directive to the streamer.
+      std::vector<MVT> Params;
+      std::vector<MVT> Locals;
+      while (Lexer.is(AsmToken::Identifier)) {
+        auto RegType = ParseRegType(Lexer.getTok().getString());
+        if (RegType == MVT::INVALID_SIMPLE_VALUE_TYPE) return true;
+        LocalTypes.push_back(RegType);
+        if (DirectiveID.getString() == ".param") {
+          Params.push_back(RegType);
+        } else {
+          Locals.push_back(RegType);
+        }
+        Parser.Lex();
+        if (!IsNext(AsmToken::Comma)) break;
+      }
+      assert(LastLabel);
+      TOut.emitParam(LastLabel, Params);
+      TOut.emitLocal(Locals);
+    } else {
+      // For now, ignore anydirective we don't recognize:
+      while (Lexer.isNot(AsmToken::EndOfStatement)) Parser.Lex();
+    }
+    return Expect(AsmToken::EndOfStatement, "EOL");
+  }
+
+  bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &/*Opcode*/,
+                               OperandVector &Operands,
+                               MCStreamer &Out, uint64_t &ErrorInfo,
+                               bool MatchingInlineAsm) override {
+    MCInst Inst;
+    unsigned MatchResult =
+        MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
+    switch (MatchResult) {
+    case Match_Success: {
+      Out.EmitInstruction(Inst, getSTI());
+      return false;
+    }
+    case Match_MissingFeature:
+      return Parser.Error(IDLoc,
+          "instruction requires a WASM feature not currently enabled");
+    case Match_MnemonicFail:
+      return Parser.Error(IDLoc, "invalid instruction");
+    case Match_NearMisses:
+      return Parser.Error(IDLoc, "ambiguous instruction");
+    case Match_InvalidTiedOperand:
+    case Match_InvalidOperand: {
+      SMLoc ErrorLoc = IDLoc;
+      if (ErrorInfo != ~0ULL) {
+        if (ErrorInfo >= Operands.size())
+          return Parser.Error(IDLoc, "too few operands for instruction");
+        ErrorLoc = Operands[ErrorInfo]->getStartLoc();
+        if (ErrorLoc == SMLoc())
+          ErrorLoc = IDLoc;
+      }
+      return Parser.Error(ErrorLoc, "invalid operand for instruction");
+    }
+    }
+    llvm_unreachable("Implement any new match types added!");
+  }
+};
+} // end anonymous namespace
+
+// Force static initialization.
+extern "C" void LLVMInitializeWebAssemblyAsmParser() {
+  RegisterMCAsmParser<WebAssemblyAsmParser> X(getTheWebAssemblyTarget32());
+  RegisterMCAsmParser<WebAssemblyAsmParser> Y(getTheWebAssemblyTarget64());
+}
+
+#define GET_REGISTER_MATCHER
+#define GET_MATCHER_IMPLEMENTATION
+#include "WebAssemblyGenAsmMatcher.inc"

Modified: llvm/trunk/lib/Target/WebAssembly/CMakeLists.txt
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Target/WebAssembly/CMakeLists.txt?rev=328028&r1=328027&r2=328028&view=diff
==============================================================================
--- llvm/trunk/lib/Target/WebAssembly/CMakeLists.txt (original)
+++ llvm/trunk/lib/Target/WebAssembly/CMakeLists.txt Tue Mar 20 13:06:35 2018
@@ -7,6 +7,7 @@ tablegen(LLVM WebAssemblyGenInstrInfo.in
 tablegen(LLVM WebAssemblyGenMCCodeEmitter.inc -gen-emitter)
 tablegen(LLVM WebAssemblyGenRegisterInfo.inc -gen-register-info)
 tablegen(LLVM WebAssemblyGenSubtargetInfo.inc -gen-subtarget)
+tablegen(LLVM WebAssemblyGenAsmMatcher.inc -gen-asm-matcher)
 add_public_tablegen_target(WebAssemblyCommonTableGen)
 
 add_llvm_target(WebAssemblyCodeGen
@@ -51,6 +52,7 @@ add_llvm_target(WebAssemblyCodeGen
   intrinsics_gen
 )
 
+add_subdirectory(AsmParser)
 add_subdirectory(Disassembler)
 add_subdirectory(InstPrinter)
 add_subdirectory(MCTargetDesc)

Modified: llvm/trunk/lib/Target/WebAssembly/InstPrinter/WebAssemblyInstPrinter.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Target/WebAssembly/InstPrinter/WebAssemblyInstPrinter.cpp?rev=328028&r1=328027&r2=328028&view=diff
==============================================================================
--- llvm/trunk/lib/Target/WebAssembly/InstPrinter/WebAssemblyInstPrinter.cpp (original)
+++ llvm/trunk/lib/Target/WebAssembly/InstPrinter/WebAssemblyInstPrinter.cpp Tue Mar 20 13:06:35 2018
@@ -82,10 +82,12 @@ void WebAssemblyInstPrinter::printInst(c
       ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false));
       break;
     case WebAssembly::END_LOOP:
-      ControlFlowStack.pop_back();
+      // Have to guard against an empty stack, in case of mismatched pairs
+      // in assembly parsing.
+      if (!ControlFlowStack.empty()) ControlFlowStack.pop_back();
       break;
     case WebAssembly::END_BLOCK:
-      printAnnotation(
+      if (!ControlFlowStack.empty()) printAnnotation(
           OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
       break;
     }

Modified: llvm/trunk/lib/Target/WebAssembly/LLVMBuild.txt
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Target/WebAssembly/LLVMBuild.txt?rev=328028&r1=328027&r2=328028&view=diff
==============================================================================
--- llvm/trunk/lib/Target/WebAssembly/LLVMBuild.txt (original)
+++ llvm/trunk/lib/Target/WebAssembly/LLVMBuild.txt Tue Mar 20 13:06:35 2018
@@ -16,12 +16,13 @@
 ;===------------------------------------------------------------------------===;
 
 [common]
-subdirectories = Disassembler InstPrinter MCTargetDesc TargetInfo
+subdirectories = AsmParser Disassembler InstPrinter MCTargetDesc TargetInfo
 
 [component_0]
 type = TargetGroup
 name = WebAssembly
 parent = Target
+has_asmparser = 1
 has_asmprinter = 1
 has_disassembler = 1
 

Modified: llvm/trunk/lib/Target/WebAssembly/WebAssembly.td
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Target/WebAssembly/WebAssembly.td?rev=328028&r1=328027&r2=328028&view=diff
==============================================================================
--- llvm/trunk/lib/Target/WebAssembly/WebAssembly.td (original)
+++ llvm/trunk/lib/Target/WebAssembly/WebAssembly.td Tue Mar 20 13:06:35 2018
@@ -80,3 +80,8 @@ def : ProcessorModel<"bleeding-edge", No
 def WebAssembly : Target {
   let InstructionSet = WebAssemblyInstrInfo;
 }
+
+def WebAssemblyAsmParser : AsmParser {
+  // The physical register names are not in the binary format or asm text
+  let ShouldEmitMatchRegisterName = 0;
+}

Modified: llvm/trunk/lib/Target/WebAssembly/WebAssemblyRegisterInfo.td
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Target/WebAssembly/WebAssemblyRegisterInfo.td?rev=328028&r1=328027&r2=328028&view=diff
==============================================================================
--- llvm/trunk/lib/Target/WebAssembly/WebAssemblyRegisterInfo.td (original)
+++ llvm/trunk/lib/Target/WebAssembly/WebAssemblyRegisterInfo.td Tue Mar 20 13:06:35 2018
@@ -34,11 +34,16 @@ def SP32 : WebAssemblyReg<"%SP32">;
 def SP64 : WebAssemblyReg<"%SP64">;
 
 // The register allocation framework requires register classes have at least
-// one register, so we define a few for the floating point register classes
-// since we otherwise don't need a physical register in those classes.
+// one register, so we define a few for the integer / floating point register
+// classes since we otherwise don't need a physical register in those classes.
+// These are also used a "types" in the generated assembly matcher.
+def I32_0 : WebAssemblyReg<"%i32.0">;
+def I64_0 : WebAssemblyReg<"%i64.0">;
 def F32_0 : WebAssemblyReg<"%f32.0">;
 def F64_0 : WebAssemblyReg<"%f64.0">;
+
 def V128_0: WebAssemblyReg<"%v128">;
+
 def EXCEPT_REF_0 : WebAssemblyReg<"%except_ref.0">;
 
 // The value stack "register". This is an opaque entity which serves to order
@@ -54,9 +59,10 @@ def ARGUMENTS : WebAssemblyReg<"ARGUMENT
 //  Register classes
 //===----------------------------------------------------------------------===//
 
-def I32 : WebAssemblyRegClass<[i32], 32, (add FP32, SP32)>;
-def I64 : WebAssemblyRegClass<[i64], 64, (add FP64, SP64)>;
+def I32 : WebAssemblyRegClass<[i32], 32, (add FP32, SP32, I32_0)>;
+def I64 : WebAssemblyRegClass<[i64], 64, (add FP64, SP64, I64_0)>;
 def F32 : WebAssemblyRegClass<[f32], 32, (add F32_0)>;
 def F64 : WebAssemblyRegClass<[f64], 64, (add F64_0)>;
 def V128 : WebAssemblyRegClass<[v4f32, v4i32, v16i8, v8i16], 128, (add V128_0)>;
 def EXCEPT_REF : WebAssemblyRegClass<[ExceptRef], 0, (add EXCEPT_REF_0)>;
+

Added: llvm/trunk/test/MC/WebAssembly/basic-assembly.s
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/MC/WebAssembly/basic-assembly.s?rev=328028&view=auto
==============================================================================
--- llvm/trunk/test/MC/WebAssembly/basic-assembly.s (added)
+++ llvm/trunk/test/MC/WebAssembly/basic-assembly.s Tue Mar 20 13:06:35 2018
@@ -0,0 +1,74 @@
+# RUN: llvm-mc -triple=wasm32-unknown-unknown-elf < %s | FileCheck %s
+
+    .text
+    .type    test0, at function
+test0:
+    # Test all types:
+    .param      i32, i64
+    .local      f32, f64  #, i8x16, i16x8, i32x4, f32x4
+    # Explicit getlocal/setlocal:
+    get_local   $push0=, 2
+    set_local   2, $pop0=
+    # Implicit locals & immediates:
+    i32.const   $0=, -1
+    f64.const   $3=, 0x1.999999999999ap1
+    # Indirect addressing:
+    get_local   $push1=, 0
+    f64.store   0($pop1), $3
+    # Loops, conditionals, binary ops, calls etc:
+    block
+    i32.const   $push2=, 1
+    get_local   $push7=, 0
+    i32.ge_s    $push0=, $pop2, $pop7
+    br_if       0, $pop0        # 0: down to label0
+.LBB0_1:
+    loop             # label1:
+    call        $drop=, something1 at FUNCTION
+    i64.const   $push10=, 1234
+    i32.call    $push8=, something2 at FUNCTION, $pop10
+    i32.const   $push11=, 0
+    call_indirect $pop11
+    i32.const   $push5=, 1
+    i32.add     $push4=, $pop8, $pop5
+    tee_local   $push3=, 0, $pop4
+    get_local   $push9=, 0
+    i32.lt_s    $push1=, $pop3, $pop9
+    br_if       0, $pop1        # 0: up to label1
+.LBB0_2:
+    end_loop
+    end_block                       # label0:
+    end_function
+
+
+# CHECK:           .text
+# CHECK-LABEL: test0:
+# CHECK-NEXT:      .param      i32, i64
+# CHECK-NEXT:      .local      f32, f64
+# CHECK-NEXT:      get_local   $push0=, 2
+# CHECK-NEXT:      set_local   2, $pop0
+# CHECK-NEXT:      i32.const   $0=, -1
+# CHECK-NEXT:      f64.const   $3=, 0x1.999999999999ap1
+# CHECK-NEXT:      get_local   $push1=, 0
+# CHECK-NEXT:      f64.store   0($pop1):p2align=0, $3
+# CHECK-NEXT:      block
+# CHECK-NEXT:      i32.const   $push2=, 1
+# CHECK-NEXT:      get_local   $push7=, 0
+# CHECK-NEXT:      i32.ge_s    $push0=, $pop2, $pop7
+# CHECK-NEXT:      br_if 0,    $pop0        # 0: down to label0
+# CHECK-NEXT:  .LBB0_1:
+# CHECK-NEXT:      loop                    # label1:
+# CHECK-NEXT:      call        something1 at FUNCTION
+# CHECK-NEXT:      i64.const   $push10=, 1234
+# CHECK-NEXT:      i32.call    $push8=, something2 at FUNCTION
+# CHECK-NEXT:      i32.const   $push11=, 0
+# CHECK-NEXT:      call_indirect
+# CHECK-NEXT:      i32.const   $push5=, 1
+# CHECK-NEXT:      i32.add     $push4=, $pop8, $pop5
+# CHECK-NEXT:      tee_local   $push3=, 0, $pop4
+# CHECK-NEXT:      get_local   $push9=, 0
+# CHECK-NEXT:      i32.lt_s    $push1=, $pop3, $pop9
+# CHECK-NEXT:      br_if 0,    $pop1        # 0: up to label1
+# CHECK-NEXT:  .LBB0_2:
+# CHECK-NEXT:      end_loop
+# CHECK-NEXT:      end_block                       # label0:
+# CHECK-NEXT:      end_function




More information about the llvm-commits mailing list