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 
16 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
17 #include "MCTargetDesc/WebAssemblyTargetStreamer.h"
18 #include "TargetInfo/WebAssemblyTargetInfo.h"
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"
24 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
25 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
26 #include "llvm/MC/MCSectionWasm.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/MC/MCSymbolWasm.h"
31 #include "llvm/Support/Endian.h"
32 #include "llvm/Support/TargetRegistry.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)
120       Inst.addOperand(MCOperand::createImm(Int.Val));
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)
132       Inst.addOperand(MCOperand::createImm(Br));
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 
291   Optional<wasm::ValType> parseType(const StringRef &Type) {
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")
307       return wasm::ValType::EXCEPT_REF;
308     return Optional<wasm::ValType>();
309   }
310 
311   WebAssembly::ExprType parseBlockType(StringRef ID) {
312     return StringSwitch<WebAssembly::ExprType>(ID)
313         .Case("i32", WebAssembly::ExprType::I32)
314         .Case("i64", WebAssembly::ExprType::I64)
315         .Case("f32", WebAssembly::ExprType::F32)
316         .Case("f64", WebAssembly::ExprType::F64)
317         .Case("v128", WebAssembly::ExprType::V128)
318         .Case("except_ref", WebAssembly::ExprType::ExceptRef)
319         .Case("void", WebAssembly::ExprType::Void)
320         .Default(WebAssembly::ExprType::Invalid);
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 checkForP2AlignIfLoadStore(OperandVector &Operands, StringRef InstName) {
348     // FIXME: there is probably a cleaner way to do this.
349     auto IsLoadStore = InstName.find(".load") != StringRef::npos ||
350                        InstName.find(".store") != StringRef::npos;
351     auto IsAtomic = InstName.find("atomic.") != StringRef::npos;
352     if (IsLoadStore || IsAtomic) {
353       // Parse load/store operands of the form: offset:p2align=align
354       if (IsLoadStore && isNext(AsmToken::Colon)) {
355         auto Id = expectIdent();
356         if (Id != "p2align")
357           return error("Expected p2align, instead got: " + Id);
358         if (expect(AsmToken::Equal, "="))
359           return true;
360         if (!Lexer.is(AsmToken::Integer))
361           return error("Expected integer constant");
362         parseSingleInteger(false, Operands);
363       } else {
364         // Alignment not specified (or atomics, must use default alignment).
365         // We can't just call WebAssembly::GetDefaultP2Align since we don't have
366         // an opcode until after the assembly matcher, so set a default to fix
367         // up later.
368         auto Tok = Lexer.getTok();
369         Operands.push_back(make_unique<WebAssemblyOperand>(
370             WebAssemblyOperand::Integer, Tok.getLoc(), Tok.getEndLoc(),
371             WebAssemblyOperand::IntOp{-1}));
372       }
373     }
374     return false;
375   }
376 
377   void addBlockTypeOperand(OperandVector &Operands, SMLoc NameLoc,
378                            WebAssembly::ExprType BT) {
379     Operands.push_back(make_unique<WebAssemblyOperand>(
380         WebAssemblyOperand::Integer, NameLoc, NameLoc,
381         WebAssemblyOperand::IntOp{static_cast<int64_t>(BT)}));
382   }
383 
384   bool ParseInstruction(ParseInstructionInfo & /*Info*/, StringRef Name,
385                         SMLoc NameLoc, OperandVector &Operands) override {
386     // Note: Name does NOT point into the sourcecode, but to a local, so
387     // use NameLoc instead.
388     Name = StringRef(NameLoc.getPointer(), Name.size());
389 
390     // WebAssembly has instructions with / in them, which AsmLexer parses
391     // as seperate tokens, so if we find such tokens immediately adjacent (no
392     // whitespace), expand the name to include them:
393     for (;;) {
394       auto &Sep = Lexer.getTok();
395       if (Sep.getLoc().getPointer() != Name.end() ||
396           Sep.getKind() != AsmToken::Slash)
397         break;
398       // Extend name with /
399       Name = StringRef(Name.begin(), Name.size() + Sep.getString().size());
400       Parser.Lex();
401       // We must now find another identifier, or error.
402       auto &Id = Lexer.getTok();
403       if (Id.getKind() != AsmToken::Identifier ||
404           Id.getLoc().getPointer() != Name.end())
405         return error("Incomplete instruction name: ", Id);
406       Name = StringRef(Name.begin(), Name.size() + Id.getString().size());
407       Parser.Lex();
408     }
409 
410     // Now construct the name as first operand.
411     Operands.push_back(make_unique<WebAssemblyOperand>(
412         WebAssemblyOperand::Token, NameLoc, SMLoc::getFromPointer(Name.end()),
413         WebAssemblyOperand::TokOp{Name}));
414 
415     // If this instruction is part of a control flow structure, ensure
416     // proper nesting.
417     bool ExpectBlockType = false;
418     if (Name == "block") {
419       push(Block);
420       ExpectBlockType = true;
421     } else if (Name == "loop") {
422       push(Loop);
423       ExpectBlockType = true;
424     } else if (Name == "try") {
425       push(Try);
426       ExpectBlockType = true;
427     } else if (Name == "if") {
428       push(If);
429       ExpectBlockType = true;
430     } else if (Name == "else") {
431       if (pop(Name, If))
432         return true;
433       push(Else);
434     } else if (Name == "catch") {
435       if (pop(Name, Try))
436         return true;
437       push(Try);
438     } else if (Name == "end_if") {
439       if (pop(Name, If, Else))
440         return true;
441     } else if (Name == "end_try") {
442       if (pop(Name, Try))
443         return true;
444     } else if (Name == "end_loop") {
445       if (pop(Name, Loop))
446         return true;
447     } else if (Name == "end_block") {
448       if (pop(Name, Block))
449         return true;
450     } else if (Name == "end_function") {
451       CurrentState = EndFunction;
452       if (pop(Name, Function) || ensureEmptyNestingStack())
453         return true;
454     }
455 
456     while (Lexer.isNot(AsmToken::EndOfStatement)) {
457       auto &Tok = Lexer.getTok();
458       switch (Tok.getKind()) {
459       case AsmToken::Identifier: {
460         auto &Id = Lexer.getTok();
461         if (ExpectBlockType) {
462           // Assume this identifier is a block_type.
463           auto BT = parseBlockType(Id.getString());
464           if (BT == WebAssembly::ExprType::Invalid)
465             return error("Unknown block type: ", Id);
466           addBlockTypeOperand(Operands, NameLoc, BT);
467           Parser.Lex();
468         } else {
469           // Assume this identifier is a label.
470           const MCExpr *Val;
471           SMLoc End;
472           if (Parser.parseExpression(Val, End))
473             return error("Cannot parse symbol: ", Lexer.getTok());
474           Operands.push_back(make_unique<WebAssemblyOperand>(
475               WebAssemblyOperand::Symbol, Id.getLoc(), Id.getEndLoc(),
476               WebAssemblyOperand::SymOp{Val}));
477           if (checkForP2AlignIfLoadStore(Operands, Name))
478             return true;
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         parseSingleInteger(true, Operands);
487         if (checkForP2AlignIfLoadStore(Operands, Name))
488           return true;
489         break;
490       case AsmToken::Integer:
491         parseSingleInteger(false, Operands);
492         if (checkForP2AlignIfLoadStore(Operands, Name))
493           return true;
494         break;
495       case AsmToken::Real: {
496         double Val;
497         if (Tok.getString().getAsDouble(Val, false))
498           return error("Cannot parse real: ", Tok);
499         Operands.push_back(make_unique<WebAssemblyOperand>(
500             WebAssemblyOperand::Float, Tok.getLoc(), Tok.getEndLoc(),
501             WebAssemblyOperand::FltOp{Val}));
502         Parser.Lex();
503         break;
504       }
505       case AsmToken::LCurly: {
506         Parser.Lex();
507         auto Op = make_unique<WebAssemblyOperand>(
508             WebAssemblyOperand::BrList, Tok.getLoc(), Tok.getEndLoc());
509         if (!Lexer.is(AsmToken::RCurly))
510           for (;;) {
511             Op->BrL.List.push_back(Lexer.getTok().getIntVal());
512             expect(AsmToken::Integer, "integer");
513             if (!isNext(AsmToken::Comma))
514               break;
515           }
516         expect(AsmToken::RCurly, "}");
517         Operands.push_back(std::move(Op));
518         break;
519       }
520       default:
521         return error("Unexpected token in operand: ", Tok);
522       }
523       if (Lexer.isNot(AsmToken::EndOfStatement)) {
524         if (expect(AsmToken::Comma, ","))
525           return true;
526       }
527     }
528     if (ExpectBlockType && Operands.size() == 1) {
529       // Support blocks with no operands as default to void.
530       addBlockTypeOperand(Operands, NameLoc, WebAssembly::ExprType::Void);
531     }
532     Parser.Lex();
533     return false;
534   }
535 
536   void onLabelParsed(MCSymbol *Symbol) override {
537     LastLabel = Symbol;
538     CurrentState = Label;
539   }
540 
541   bool parseSignature(wasm::WasmSignature *Signature) {
542     if (expect(AsmToken::LParen, "("))
543       return true;
544     if (parseRegTypeList(Signature->Params))
545       return true;
546     if (expect(AsmToken::RParen, ")"))
547       return true;
548     if (expect(AsmToken::MinusGreater, "->"))
549       return true;
550     if (expect(AsmToken::LParen, "("))
551       return true;
552     if (parseRegTypeList(Signature->Returns))
553       return true;
554     if (expect(AsmToken::RParen, ")"))
555       return true;
556     return false;
557   }
558 
559   bool CheckDataSection() {
560     if (CurrentState != DataSection) {
561       auto WS = cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
562       if (WS && WS->getKind().isText())
563         return error("data directive must occur in a data segment: ",
564                      Lexer.getTok());
565     }
566     CurrentState = DataSection;
567     return false;
568   }
569 
570   // This function processes wasm-specific directives streamed to
571   // WebAssemblyTargetStreamer, all others go to the generic parser
572   // (see WasmAsmParser).
573   bool ParseDirective(AsmToken DirectiveID) override {
574     // This function has a really weird return value behavior that is different
575     // from all the other parsing functions:
576     // - return true && no tokens consumed -> don't know this directive / let
577     //   the generic parser handle it.
578     // - return true && tokens consumed -> a parsing error occurred.
579     // - return false -> processed this directive successfully.
580     assert(DirectiveID.getKind() == AsmToken::Identifier);
581     auto &Out = getStreamer();
582     auto &TOut =
583         reinterpret_cast<WebAssemblyTargetStreamer &>(*Out.getTargetStreamer());
584     auto &Ctx = Out.getContext();
585 
586     // TODO: any time we return an error, at least one token must have been
587     // consumed, otherwise this will not signal an error to the caller.
588     if (DirectiveID.getString() == ".globaltype") {
589       auto SymName = expectIdent();
590       if (SymName.empty())
591         return true;
592       if (expect(AsmToken::Comma, ","))
593         return true;
594       auto TypeTok = Lexer.getTok();
595       auto TypeName = expectIdent();
596       if (TypeName.empty())
597         return true;
598       auto Type = parseType(TypeName);
599       if (!Type)
600         return error("Unknown type in .globaltype directive: ", TypeTok);
601       // Now set this symbol with the correct type.
602       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
603       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
604       WasmSym->setGlobalType(
605           wasm::WasmGlobalType{uint8_t(Type.getValue()), true});
606       // And emit the directive again.
607       TOut.emitGlobalType(WasmSym);
608       return expect(AsmToken::EndOfStatement, "EOL");
609     }
610 
611     if (DirectiveID.getString() == ".functype") {
612       // This code has to send things to the streamer similar to
613       // WebAssemblyAsmPrinter::EmitFunctionBodyStart.
614       // TODO: would be good to factor this into a common function, but the
615       // assembler and backend really don't share any common code, and this code
616       // parses the locals seperately.
617       auto SymName = expectIdent();
618       if (SymName.empty())
619         return true;
620       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
621       if (CurrentState == Label && WasmSym == LastLabel) {
622         // This .functype indicates a start of a function.
623         if (ensureEmptyNestingStack())
624           return true;
625         CurrentState = FunctionStart;
626         LastFunctionLabel = LastLabel;
627         push(Function);
628       }
629       auto Signature = make_unique<wasm::WasmSignature>();
630       if (parseSignature(Signature.get()))
631         return true;
632       WasmSym->setSignature(Signature.get());
633       addSignature(std::move(Signature));
634       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
635       TOut.emitFunctionType(WasmSym);
636       // TODO: backend also calls TOut.emitIndIdx, but that is not implemented.
637       return expect(AsmToken::EndOfStatement, "EOL");
638     }
639 
640     if (DirectiveID.getString() == ".eventtype") {
641       auto SymName = expectIdent();
642       if (SymName.empty())
643         return true;
644       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
645       auto Signature = make_unique<wasm::WasmSignature>();
646       if (parseRegTypeList(Signature->Params))
647         return true;
648       WasmSym->setSignature(Signature.get());
649       addSignature(std::move(Signature));
650       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_EVENT);
651       TOut.emitEventType(WasmSym);
652       // TODO: backend also calls TOut.emitIndIdx, but that is not implemented.
653       return expect(AsmToken::EndOfStatement, "EOL");
654     }
655 
656     if (DirectiveID.getString() == ".local") {
657       if (CurrentState != FunctionStart)
658         return error(".local directive should follow the start of a function",
659                      Lexer.getTok());
660       SmallVector<wasm::ValType, 4> Locals;
661       if (parseRegTypeList(Locals))
662         return true;
663       TOut.emitLocal(Locals);
664       CurrentState = FunctionLocals;
665       return expect(AsmToken::EndOfStatement, "EOL");
666     }
667 
668     if (DirectiveID.getString() == ".int8" ||
669         DirectiveID.getString() == ".int16" ||
670         DirectiveID.getString() == ".int32" ||
671         DirectiveID.getString() == ".int64") {
672       if (CheckDataSection()) return true;
673       const MCExpr *Val;
674       SMLoc End;
675       if (Parser.parseExpression(Val, End))
676         return error("Cannot parse .int expression: ", Lexer.getTok());
677       size_t NumBits = 0;
678       DirectiveID.getString().drop_front(4).getAsInteger(10, NumBits);
679       Out.EmitValue(Val, NumBits / 8, End);
680       return expect(AsmToken::EndOfStatement, "EOL");
681     }
682 
683     if (DirectiveID.getString() == ".asciz") {
684       if (CheckDataSection()) return true;
685       std::string S;
686       if (Parser.parseEscapedString(S))
687         return error("Cannot parse string constant: ", Lexer.getTok());
688       Out.EmitBytes(StringRef(S.c_str(), S.length() + 1));
689       return expect(AsmToken::EndOfStatement, "EOL");
690     }
691 
692     return true; // We didn't process this directive.
693   }
694 
695   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned & /*Opcode*/,
696                                OperandVector &Operands, MCStreamer &Out,
697                                uint64_t &ErrorInfo,
698                                bool MatchingInlineAsm) override {
699     MCInst Inst;
700     unsigned MatchResult =
701         MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
702     switch (MatchResult) {
703     case Match_Success: {
704       if (CurrentState == FunctionStart) {
705         // This is the first instruction in a function, but we haven't seen
706         // a .local directive yet. The streamer requires locals to be encoded
707         // as a prelude to the instructions, so emit an empty list of locals
708         // here.
709         auto &TOut = reinterpret_cast<WebAssemblyTargetStreamer &>(
710             *Out.getTargetStreamer());
711         TOut.emitLocal(SmallVector<wasm::ValType, 0>());
712       }
713       // Fix unknown p2align operands.
714       auto Align = WebAssembly::GetDefaultP2AlignAny(Inst.getOpcode());
715       if (Align != -1U) {
716         auto &Op0 = Inst.getOperand(0);
717         if (Op0.getImm() == -1)
718           Op0.setImm(Align);
719       }
720       Out.EmitInstruction(Inst, getSTI());
721       if (CurrentState == EndFunction) {
722         onEndOfFunction();
723       } else {
724         CurrentState = Instructions;
725       }
726       return false;
727     }
728     case Match_MissingFeature:
729       return Parser.Error(
730           IDLoc, "instruction requires a WASM feature not currently enabled");
731     case Match_MnemonicFail:
732       return Parser.Error(IDLoc, "invalid instruction");
733     case Match_NearMisses:
734       return Parser.Error(IDLoc, "ambiguous instruction");
735     case Match_InvalidTiedOperand:
736     case Match_InvalidOperand: {
737       SMLoc ErrorLoc = IDLoc;
738       if (ErrorInfo != ~0ULL) {
739         if (ErrorInfo >= Operands.size())
740           return Parser.Error(IDLoc, "too few operands for instruction");
741         ErrorLoc = Operands[ErrorInfo]->getStartLoc();
742         if (ErrorLoc == SMLoc())
743           ErrorLoc = IDLoc;
744       }
745       return Parser.Error(ErrorLoc, "invalid operand for instruction");
746     }
747     }
748     llvm_unreachable("Implement any new match types added!");
749   }
750 
751   void doBeforeLabelEmit(MCSymbol *Symbol) override {
752     // Start a new section for the next function automatically, since our
753     // object writer expects each function to have its own section. This way
754     // The user can't forget this "convention".
755     auto SymName = Symbol->getName();
756     if (SymName.startswith(".L"))
757       return; // Local Symbol.
758     // Only create a new text section if we're already in one.
759     auto CWS = cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
760     if (!CWS || !CWS->getKind().isText())
761       return;
762     auto SecName = ".text." + SymName;
763     auto WS = getContext().getWasmSection(SecName, SectionKind::getText());
764     getStreamer().SwitchSection(WS);
765   }
766 
767   void onEndOfFunction() {
768     // Automatically output a .size directive, so it becomes optional for the
769     // user.
770     if (!LastFunctionLabel) return;
771     auto TempSym = getContext().createLinkerPrivateTempSymbol();
772     getStreamer().EmitLabel(TempSym);
773     auto Start = MCSymbolRefExpr::create(LastFunctionLabel, getContext());
774     auto End = MCSymbolRefExpr::create(TempSym, getContext());
775     auto Expr =
776         MCBinaryExpr::create(MCBinaryExpr::Sub, End, Start, getContext());
777     getStreamer().emitELFSize(LastFunctionLabel, Expr);
778   }
779 
780   void onEndOfFile() override { ensureEmptyNestingStack(); }
781 };
782 } // end anonymous namespace
783 
784 // Force static initialization.
785 extern "C" void LLVMInitializeWebAssemblyAsmParser() {
786   RegisterMCAsmParser<WebAssemblyAsmParser> X(getTheWebAssemblyTarget32());
787   RegisterMCAsmParser<WebAssemblyAsmParser> Y(getTheWebAssemblyTarget64());
788 }
789 
790 #define GET_REGISTER_MATCHER
791 #define GET_MATCHER_IMPLEMENTATION
792 #include "WebAssemblyGenAsmMatcher.inc"
793