1 //==- WebAssemblyAsmParser.cpp - Assembler for WebAssembly -*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file is part of the WebAssembly Assembler.
13 /// It contains code to translate a parsed .s file into MCInsts.
15 //===----------------------------------------------------------------------===//
17 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
18 #include "MCTargetDesc/WebAssemblyTargetStreamer.h"
19 #include "WebAssembly.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
22 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/Support/Endian.h"
29 #include "llvm/Support/TargetRegistry.h"
33 #define DEBUG_TYPE "wasm-asm-parser"
37 // We store register types as SimpleValueType to retain SIMD layout
38 // information, but must also be able to supply them as the (unnamed)
39 // register enum from WebAssemblyRegisterInfo.td/.inc.
40 static unsigned MVTToWasmReg(MVT::SimpleValueType Type) {
42 case MVT::i32: return WebAssembly::I32_0;
43 case MVT::i64: return WebAssembly::I64_0;
44 case MVT::f32: return WebAssembly::F32_0;
45 case MVT::f64: return WebAssembly::F64_0;
46 case MVT::v16i8: return WebAssembly::V128_0;
47 case MVT::v8i16: return WebAssembly::V128_0;
48 case MVT::v4i32: return WebAssembly::V128_0;
49 case MVT::v4f32: return WebAssembly::V128_0;
50 default: return MVT::INVALID_SIMPLE_VALUE_TYPE;
54 /// WebAssemblyOperand - Instances of this class represent the operands in a
55 /// parsed WASM machine instruction.
56 struct WebAssemblyOperand : public MCParsedAsmOperand {
57 enum KindTy { Token, Local, Stack, Integer, Float, Symbol } Kind;
59 SMLoc StartLoc, EndLoc;
66 // This is a (virtual) local or stack register represented as 0..
68 // In most targets, the register number also encodes the type, but for
69 // wasm we have to track that seperately since we have an unbounded
70 // number of registers.
71 // This has the unfortunate side effect that we supply a different value
72 // to the table-gen matcher at different times in the process (when it
73 // calls getReg() or addRegOperands().
74 // TODO: While this works, it feels brittle. and would be nice to clean up.
75 MVT::SimpleValueType Type;
98 WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, TokOp T)
99 : Kind(K), StartLoc(Start), EndLoc(End), Tok(T) {}
100 WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, RegOp R)
101 : Kind(K), StartLoc(Start), EndLoc(End), Reg(R) {}
102 WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, IntOp I)
103 : Kind(K), StartLoc(Start), EndLoc(End), Int(I) {}
104 WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, FltOp F)
105 : Kind(K), StartLoc(Start), EndLoc(End), Flt(F) {}
106 WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, SymOp S)
107 : Kind(K), StartLoc(Start), EndLoc(End), Sym(S) {}
109 bool isToken() const override { return Kind == Token; }
110 bool isImm() const override { return Kind == Integer ||
113 bool isReg() const override { return Kind == Local || Kind == Stack; }
114 bool isMem() const override { return false; }
116 unsigned getReg() const override {
118 // This is called from the tablegen matcher (MatchInstructionImpl)
119 // where it expects to match the type of register, see RegOp above.
120 return MVTToWasmReg(Reg.Type);
123 StringRef getToken() const {
128 SMLoc getStartLoc() const override { return StartLoc; }
129 SMLoc getEndLoc() const override { return EndLoc; }
131 void addRegOperands(MCInst &Inst, unsigned N) const {
132 assert(N == 1 && "Invalid number of operands!");
133 assert(isReg() && "Not a register operand!");
134 // This is called from the tablegen matcher (MatchInstructionImpl)
135 // where it expects to output the actual register index, see RegOp above.
136 unsigned R = Reg.RegNo;
138 // A stack register is represented as a large negative number.
139 // See WebAssemblyRegNumbering::runOnMachineFunction and
140 // getWARegStackId for why this | is needed.
143 Inst.addOperand(MCOperand::createReg(R));
146 void addImmOperands(MCInst &Inst, unsigned N) const {
147 assert(N == 1 && "Invalid number of operands!");
149 Inst.addOperand(MCOperand::createImm(Int.Val));
150 else if (Kind == Float)
151 Inst.addOperand(MCOperand::createFPImm(Flt.Val));
152 else if (Kind == Symbol)
153 Inst.addOperand(MCOperand::createExpr(Sym.Exp));
155 llvm_unreachable("Should be immediate or symbol!");
158 void print(raw_ostream &OS) const override {
161 OS << "Tok:" << Tok.Tok;
164 OS << "Loc:" << Reg.RegNo << ":" << static_cast<int>(Reg.Type);
167 OS << "Stk:" << Reg.RegNo << ":" << static_cast<int>(Reg.Type);
170 OS << "Int:" << Int.Val;
173 OS << "Flt:" << Flt.Val;
176 OS << "Sym:" << Sym.Exp;
182 class WebAssemblyAsmParser final : public MCTargetAsmParser {
185 // These are for the current function being parsed:
186 // These are vectors since register assignments are so far non-sparse.
187 // Replace by map if necessary.
188 std::vector<MVT::SimpleValueType> LocalTypes;
189 std::vector<MVT::SimpleValueType> StackTypes;
193 WebAssemblyAsmParser(const MCSubtargetInfo &sti, MCAsmParser &Parser,
194 const MCInstrInfo &mii, const MCTargetOptions &Options)
195 : MCTargetAsmParser(Options, sti, mii), Parser(Parser),
196 Lexer(Parser.getLexer()), LastLabel(nullptr) {
199 #define GET_ASSEMBLER_HEADER
200 #include "WebAssemblyGenAsmMatcher.inc"
202 // TODO: This is required to be implemented, but appears unused.
203 bool ParseRegister(unsigned &/*RegNo*/, SMLoc &/*StartLoc*/,
204 SMLoc &/*EndLoc*/) override {
205 llvm_unreachable("ParseRegister is not implemented.");
208 bool Error(const StringRef &msg, const AsmToken &tok) {
209 return Parser.Error(tok.getLoc(), msg + tok.getString());
212 bool IsNext(AsmToken::TokenKind Kind) {
213 auto ok = Lexer.is(Kind);
214 if (ok) Parser.Lex();
218 bool Expect(AsmToken::TokenKind Kind, const char *KindName) {
220 return Error(std::string("Expected ") + KindName + ", instead got: ",
225 MVT::SimpleValueType ParseRegType(const StringRef &RegType) {
226 // Derive type from .param .local decls, or the instruction itself.
227 return StringSwitch<MVT::SimpleValueType>(RegType)
228 .Case("i32", MVT::i32)
229 .Case("i64", MVT::i64)
230 .Case("f32", MVT::f32)
231 .Case("f64", MVT::f64)
232 .Case("i8x16", MVT::v16i8)
233 .Case("i16x8", MVT::v8i16)
234 .Case("i32x4", MVT::v4i32)
235 .Case("f32x4", MVT::v4f32)
236 .Default(MVT::INVALID_SIMPLE_VALUE_TYPE);
239 MVT::SimpleValueType &GetType(
240 std::vector<MVT::SimpleValueType> &Types, size_t i) {
241 Types.resize(std::max(i + 1, Types.size()), MVT::INVALID_SIMPLE_VALUE_TYPE);
245 bool ParseReg(OperandVector &Operands, StringRef TypePrefix) {
246 if (Lexer.is(AsmToken::Integer)) {
247 auto &Local = Lexer.getTok();
248 // This is a reference to a local, turn it into a virtual register.
249 auto LocalNo = static_cast<unsigned>(Local.getIntVal());
250 Operands.push_back(make_unique<WebAssemblyOperand>(
251 WebAssemblyOperand::Local, Local.getLoc(),
253 WebAssemblyOperand::RegOp{LocalNo,
254 GetType(LocalTypes, LocalNo)}));
256 } else if (Lexer.is(AsmToken::Identifier)) {
257 auto &StackRegTok = Lexer.getTok();
258 // These are push/pop/drop pseudo stack registers, which we turn
259 // into virtual registers also. The stackify pass will later turn them
260 // back into implicit stack references if possible.
261 auto StackReg = StackRegTok.getString();
262 auto StackOp = StackReg.take_while([](char c) { return isalpha(c); });
263 auto Reg = StackReg.drop_front(StackOp.size());
264 unsigned long long ParsedRegNo = 0;
265 if (!Reg.empty() && getAsUnsignedInteger(Reg, 10, ParsedRegNo))
266 return Error("Cannot parse stack register index: ", StackRegTok);
267 unsigned RegNo = static_cast<unsigned>(ParsedRegNo);
268 if (StackOp == "push") {
269 // This defines a result, record register type.
270 auto RegType = ParseRegType(TypePrefix);
271 GetType(StackTypes, RegNo) = RegType;
272 Operands.push_back(make_unique<WebAssemblyOperand>(
273 WebAssemblyOperand::Stack,
274 StackRegTok.getLoc(),
275 StackRegTok.getEndLoc(),
276 WebAssemblyOperand::RegOp{RegNo, RegType}));
277 } else if (StackOp == "pop") {
278 // This uses a previously defined stack value.
279 auto RegType = GetType(StackTypes, RegNo);
280 Operands.push_back(make_unique<WebAssemblyOperand>(
281 WebAssemblyOperand::Stack,
282 StackRegTok.getLoc(),
283 StackRegTok.getEndLoc(),
284 WebAssemblyOperand::RegOp{RegNo, RegType}));
285 } else if (StackOp == "drop") {
286 // This operand will be dropped, since it is part of an instruction
287 // whose result is void.
289 return Error("Unknown stack register prefix: ", StackRegTok);
294 "Expected identifier/integer following $, instead got: ",
297 IsNext(AsmToken::Equal);
301 void ParseSingleInteger(bool IsNegative, OperandVector &Operands) {
302 auto &Int = Lexer.getTok();
303 int64_t Val = Int.getIntVal();
304 if (IsNegative) Val = -Val;
305 Operands.push_back(make_unique<WebAssemblyOperand>(
306 WebAssemblyOperand::Integer, Int.getLoc(),
307 Int.getEndLoc(), WebAssemblyOperand::IntOp{Val}));
311 bool ParseOperandStartingWithInteger(bool IsNegative,
312 OperandVector &Operands,
313 StringRef InstType) {
314 ParseSingleInteger(IsNegative, Operands);
315 if (Lexer.is(AsmToken::LParen)) {
316 // Parse load/store operands of the form: offset($reg)align
317 auto &LParen = Lexer.getTok();
319 make_unique<WebAssemblyOperand>(WebAssemblyOperand::Token,
322 WebAssemblyOperand::TokOp{
323 LParen.getString()}));
325 if (Expect(AsmToken::Dollar, "register")) return true;
326 if (ParseReg(Operands, InstType)) return true;
327 auto &RParen = Lexer.getTok();
329 make_unique<WebAssemblyOperand>(WebAssemblyOperand::Token,
332 WebAssemblyOperand::TokOp{
333 RParen.getString()}));
334 if (Expect(AsmToken::RParen, ")")) return true;
335 if (Lexer.is(AsmToken::Integer)) {
336 ParseSingleInteger(false, Operands);
338 // Alignment not specified.
339 // FIXME: correctly derive a default from the instruction.
340 Operands.push_back(make_unique<WebAssemblyOperand>(
341 WebAssemblyOperand::Integer, RParen.getLoc(),
342 RParen.getEndLoc(), WebAssemblyOperand::IntOp{0}));
348 bool ParseInstruction(ParseInstructionInfo &/*Info*/, StringRef Name,
349 SMLoc NameLoc, OperandVector &Operands) override {
351 make_unique<WebAssemblyOperand>(WebAssemblyOperand::Token, NameLoc,
352 SMLoc::getFromPointer(
353 NameLoc.getPointer() + Name.size()),
354 WebAssemblyOperand::TokOp{
355 StringRef(NameLoc.getPointer(),
357 auto NamePair = Name.split('.');
358 // If no '.', there is no type prefix.
359 if (NamePair.second.empty()) std::swap(NamePair.first, NamePair.second);
360 while (Lexer.isNot(AsmToken::EndOfStatement)) {
361 auto &Tok = Lexer.getTok();
362 switch (Tok.getKind()) {
363 case AsmToken::Dollar: {
365 if (ParseReg(Operands, NamePair.first)) return true;
368 case AsmToken::Identifier: {
369 auto &Id = Lexer.getTok();
372 if (Parser.parsePrimaryExpr(Val, End))
373 return Error("Cannot parse symbol: ", Lexer.getTok());
374 Operands.push_back(make_unique<WebAssemblyOperand>(
375 WebAssemblyOperand::Symbol, Id.getLoc(),
376 Id.getEndLoc(), WebAssemblyOperand::SymOp{Val}));
379 case AsmToken::Minus:
381 if (Lexer.isNot(AsmToken::Integer))
382 return Error("Expected integer instead got: ", Lexer.getTok());
383 if (ParseOperandStartingWithInteger(true, Operands, NamePair.first))
386 case AsmToken::Integer:
387 if (ParseOperandStartingWithInteger(false, Operands, NamePair.first))
390 case AsmToken::Real: {
392 if (Tok.getString().getAsDouble(Val, false))
393 return Error("Cannot parse real: ", Tok);
394 Operands.push_back(make_unique<WebAssemblyOperand>(
395 WebAssemblyOperand::Float, Tok.getLoc(),
396 Tok.getEndLoc(), WebAssemblyOperand::FltOp{Val}));
401 return Error("Unexpected token in operand: ", Tok);
403 if (Lexer.isNot(AsmToken::EndOfStatement)) {
404 if (Expect(AsmToken::Comma, ",")) return true;
408 // Call instructions are vararg, but the tablegen matcher doesn't seem to
409 // support that, so for now we strip these extra operands.
410 // This is problematic if these arguments are not simple $pop stack
411 // registers, since e.g. a local register would get lost, so we check for
412 // this. This can be the case when using -disable-wasm-explicit-locals
413 // which currently s2wasm requires.
414 // TODO: Instead, we can move this code to MatchAndEmitInstruction below and
415 // actually generate get_local instructions on the fly.
416 // Or even better, improve the matcher to support vararg?
417 auto IsIndirect = NamePair.second == "call_indirect";
418 if (IsIndirect || NamePair.second == "call") {
419 // Figure out number of fixed operands from the instruction.
420 size_t CallOperands = 1; // The name token.
421 if (!IsIndirect) CallOperands++; // The function index.
422 if (!NamePair.first.empty()) CallOperands++; // The result register.
423 if (Operands.size() > CallOperands) {
424 // Ensure operands we drop are all $pop.
425 for (size_t I = CallOperands; I < Operands.size(); I++) {
427 reinterpret_cast<WebAssemblyOperand *>(Operands[I].get());
428 if (Operand->Kind != WebAssemblyOperand::Stack)
429 Parser.Error(NameLoc,
430 "Call instruction has non-stack arguments, if this code was "
431 "generated with -disable-wasm-explicit-locals please remove it");
433 // Drop unneeded operands.
434 Operands.resize(CallOperands);
437 // Block instructions require a signature index, but these are missing in
438 // assembly, so we add a dummy one explicitly (since we have no control
439 // over signature tables here, we assume these will be regenerated when
440 // the wasm module is generated).
441 if (NamePair.second == "block" || NamePair.second == "loop") {
442 Operands.push_back(make_unique<WebAssemblyOperand>(
443 WebAssemblyOperand::Integer, NameLoc,
444 NameLoc, WebAssemblyOperand::IntOp{-1}));
446 // These don't specify the type, which has to derived from the local index.
447 if (NamePair.second == "get_local" || NamePair.second == "tee_local") {
448 if (Operands.size() >= 3 && Operands[1]->isReg() &&
449 Operands[2]->isImm()) {
450 auto Op1 = reinterpret_cast<WebAssemblyOperand *>(Operands[1].get());
451 auto Op2 = reinterpret_cast<WebAssemblyOperand *>(Operands[2].get());
452 auto Type = GetType(LocalTypes, static_cast<size_t>(Op2->Int.Val));
453 Op1->Reg.Type = Type;
454 GetType(StackTypes, Op1->Reg.RegNo) = Type;
460 void onLabelParsed(MCSymbol *Symbol) override {
464 bool ParseDirective(AsmToken DirectiveID) override {
465 assert(DirectiveID.getKind() == AsmToken::Identifier);
466 auto &Out = getStreamer();
467 auto &TOut = reinterpret_cast<WebAssemblyTargetStreamer &>(
468 *Out.getTargetStreamer());
469 // TODO: we're just parsing the subset of directives we're interested in,
470 // and ignoring ones we don't recognise. We should ideally verify
471 // all directives here.
472 if (DirectiveID.getString() == ".type") {
473 // This could be the start of a function, check if followed by
475 if (!(IsNext(AsmToken::Identifier) &&
476 IsNext(AsmToken::Comma) &&
477 IsNext(AsmToken::At) &&
478 Lexer.is(AsmToken::Identifier)))
479 return Error("Expected label,@type declaration, got: ", Lexer.getTok());
480 if (Lexer.getTok().getString() == "function") {
481 // Track locals from start of function.
486 //Out.EmitSymbolAttribute(??, MCSA_ELF_TypeFunction);
487 } else if (DirectiveID.getString() == ".param" ||
488 DirectiveID.getString() == ".local") {
489 // Track the number of locals, needed for correct virtual register
490 // assignment elsewhere.
491 // Also output a directive to the streamer.
492 std::vector<MVT> Params;
493 std::vector<MVT> Locals;
494 while (Lexer.is(AsmToken::Identifier)) {
495 auto RegType = ParseRegType(Lexer.getTok().getString());
496 if (RegType == MVT::INVALID_SIMPLE_VALUE_TYPE) return true;
497 LocalTypes.push_back(RegType);
498 if (DirectiveID.getString() == ".param") {
499 Params.push_back(RegType);
501 Locals.push_back(RegType);
504 if (!IsNext(AsmToken::Comma)) break;
507 TOut.emitParam(LastLabel, Params);
508 TOut.emitLocal(Locals);
510 // For now, ignore anydirective we don't recognize:
511 while (Lexer.isNot(AsmToken::EndOfStatement)) Parser.Lex();
513 return Expect(AsmToken::EndOfStatement, "EOL");
516 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &/*Opcode*/,
517 OperandVector &Operands,
518 MCStreamer &Out, uint64_t &ErrorInfo,
519 bool MatchingInlineAsm) override {
521 unsigned MatchResult =
522 MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
523 switch (MatchResult) {
524 case Match_Success: {
525 Out.EmitInstruction(Inst, getSTI());
528 case Match_MissingFeature:
529 return Parser.Error(IDLoc,
530 "instruction requires a WASM feature not currently enabled");
531 case Match_MnemonicFail:
532 return Parser.Error(IDLoc, "invalid instruction");
533 case Match_NearMisses:
534 return Parser.Error(IDLoc, "ambiguous instruction");
535 case Match_InvalidTiedOperand:
536 case Match_InvalidOperand: {
537 SMLoc ErrorLoc = IDLoc;
538 if (ErrorInfo != ~0ULL) {
539 if (ErrorInfo >= Operands.size())
540 return Parser.Error(IDLoc, "too few operands for instruction");
541 ErrorLoc = Operands[ErrorInfo]->getStartLoc();
542 if (ErrorLoc == SMLoc())
545 return Parser.Error(ErrorLoc, "invalid operand for instruction");
548 llvm_unreachable("Implement any new match types added!");
551 } // end anonymous namespace
553 // Force static initialization.
554 extern "C" void LLVMInitializeWebAssemblyAsmParser() {
555 RegisterMCAsmParser<WebAssemblyAsmParser> X(getTheWebAssemblyTarget32());
556 RegisterMCAsmParser<WebAssemblyAsmParser> Y(getTheWebAssemblyTarget64());
559 #define GET_REGISTER_MATCHER
560 #define GET_MATCHER_IMPLEMENTATION
561 #include "WebAssemblyGenAsmMatcher.inc"