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 { return Kind == Integer || Kind == Symbol; }
93   bool isFPImm() const { return Kind == Float; }
94   bool isMem() const override { return false; }
95   bool isReg() const override { return false; }
96   bool isBrList() const { return Kind == BrList; }
97 
98   unsigned getReg() const override {
99     llvm_unreachable("Assembly inspects a register operand");
100     return 0;
101   }
102 
103   StringRef getToken() const {
104     assert(isToken());
105     return Tok.Tok;
106   }
107 
108   SMLoc getStartLoc() const override { return StartLoc; }
109   SMLoc getEndLoc() const override { return EndLoc; }
110 
111   void addRegOperands(MCInst &, unsigned) const {
112     // Required by the assembly matcher.
113     llvm_unreachable("Assembly matcher creates register operands");
114   }
115 
116   void addImmOperands(MCInst &Inst, unsigned N) const {
117     assert(N == 1 && "Invalid number of operands!");
118     if (Kind == Integer)
119       Inst.addOperand(MCOperand::createImm(Int.Val));
120     else if (Kind == Symbol)
121       Inst.addOperand(MCOperand::createExpr(Sym.Exp));
122     else
123       llvm_unreachable("Should be integer immediate or symbol!");
124   }
125 
126   void addFPImmOperands(MCInst &Inst, unsigned N) const {
127     assert(N == 1 && "Invalid number of operands!");
128     if (Kind == Float)
129       Inst.addOperand(MCOperand::createFPImm(Flt.Val));
130     else
131       llvm_unreachable("Should be float immediate!");
132   }
133 
134   void addBrListOperands(MCInst &Inst, unsigned N) const {
135     assert(N == 1 && isBrList() && "Invalid BrList!");
136     for (auto Br : BrL.List)
137       Inst.addOperand(MCOperand::createImm(Br));
138   }
139 
140   void print(raw_ostream &OS) const override {
141     switch (Kind) {
142     case Token:
143       OS << "Tok:" << Tok.Tok;
144       break;
145     case Integer:
146       OS << "Int:" << Int.Val;
147       break;
148     case Float:
149       OS << "Flt:" << Flt.Val;
150       break;
151     case Symbol:
152       OS << "Sym:" << Sym.Exp;
153       break;
154     case BrList:
155       OS << "BrList:" << BrL.List.size();
156       break;
157     }
158   }
159 };
160 
161 class WebAssemblyAsmParser final : public MCTargetAsmParser {
162   MCAsmParser &Parser;
163   MCAsmLexer &Lexer;
164 
165   // Much like WebAssemblyAsmPrinter in the backend, we have to own these.
166   std::vector<std::unique_ptr<wasm::WasmSignature>> Signatures;
167 
168   // Order of labels, directives and instructions in a .s file have no
169   // syntactical enforcement. This class is a callback from the actual parser,
170   // and yet we have to be feeding data to the streamer in a very particular
171   // order to ensure a correct binary encoding that matches the regular backend
172   // (the streamer does not enforce this). This "state machine" enum helps
173   // guarantee that correct order.
174   enum ParserState {
175     FileStart,
176     Label,
177     FunctionStart,
178     FunctionLocals,
179     Instructions,
180     EndFunction,
181     DataSection,
182   } CurrentState = FileStart;
183 
184   // For ensuring blocks are properly nested.
185   enum NestingType {
186     Function,
187     Block,
188     Loop,
189     Try,
190     If,
191     Else,
192     Undefined,
193   };
194   std::vector<NestingType> NestingStack;
195 
196   // We track this to see if a .functype following a label is the same,
197   // as this is how we recognize the start of a function.
198   MCSymbol *LastLabel = nullptr;
199   MCSymbol *LastFunctionLabel = nullptr;
200 
201 public:
202   WebAssemblyAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
203                        const MCInstrInfo &MII, const MCTargetOptions &Options)
204       : MCTargetAsmParser(Options, STI, MII), Parser(Parser),
205         Lexer(Parser.getLexer()) {
206     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
207   }
208 
209 #define GET_ASSEMBLER_HEADER
210 #include "WebAssemblyGenAsmMatcher.inc"
211 
212   // TODO: This is required to be implemented, but appears unused.
213   bool ParseRegister(unsigned & /*RegNo*/, SMLoc & /*StartLoc*/,
214                      SMLoc & /*EndLoc*/) override {
215     llvm_unreachable("ParseRegister is not implemented.");
216   }
217 
218   bool error(const Twine &Msg, const AsmToken &Tok) {
219     return Parser.Error(Tok.getLoc(), Msg + Tok.getString());
220   }
221 
222   bool error(const Twine &Msg) {
223     return Parser.Error(Lexer.getTok().getLoc(), Msg);
224   }
225 
226   void addSignature(std::unique_ptr<wasm::WasmSignature> &&Sig) {
227     Signatures.push_back(std::move(Sig));
228   }
229 
230   std::pair<StringRef, StringRef> nestingString(NestingType NT) {
231     switch (NT) {
232     case Function:
233       return {"function", "end_function"};
234     case Block:
235       return {"block", "end_block"};
236     case Loop:
237       return {"loop", "end_loop"};
238     case Try:
239       return {"try", "end_try"};
240     case If:
241       return {"if", "end_if"};
242     case Else:
243       return {"else", "end_if"};
244     default:
245       llvm_unreachable("unknown NestingType");
246     }
247   }
248 
249   void push(NestingType NT) { NestingStack.push_back(NT); }
250 
251   bool pop(StringRef Ins, NestingType NT1, NestingType NT2 = Undefined) {
252     if (NestingStack.empty())
253       return error(Twine("End of block construct with no start: ") + Ins);
254     auto Top = NestingStack.back();
255     if (Top != NT1 && Top != NT2)
256       return error(Twine("Block construct type mismatch, expected: ") +
257                    nestingString(Top).second + ", instead got: " + Ins);
258     NestingStack.pop_back();
259     return false;
260   }
261 
262   bool ensureEmptyNestingStack() {
263     auto Err = !NestingStack.empty();
264     while (!NestingStack.empty()) {
265       error(Twine("Unmatched block construct(s) at function end: ") +
266             nestingString(NestingStack.back()).first);
267       NestingStack.pop_back();
268     }
269     return Err;
270   }
271 
272   bool isNext(AsmToken::TokenKind Kind) {
273     auto Ok = Lexer.is(Kind);
274     if (Ok)
275       Parser.Lex();
276     return Ok;
277   }
278 
279   bool expect(AsmToken::TokenKind Kind, const char *KindName) {
280     if (!isNext(Kind))
281       return error(std::string("Expected ") + KindName + ", instead got: ",
282                    Lexer.getTok());
283     return false;
284   }
285 
286   StringRef expectIdent() {
287     if (!Lexer.is(AsmToken::Identifier)) {
288       error("Expected identifier, got: ", Lexer.getTok());
289       return StringRef();
290     }
291     auto Name = Lexer.getTok().getString();
292     Parser.Lex();
293     return Name;
294   }
295 
296   Optional<wasm::ValType> parseType(const StringRef &Type) {
297     // FIXME: can't use StringSwitch because wasm::ValType doesn't have a
298     // "invalid" value.
299     if (Type == "i32")
300       return wasm::ValType::I32;
301     if (Type == "i64")
302       return wasm::ValType::I64;
303     if (Type == "f32")
304       return wasm::ValType::F32;
305     if (Type == "f64")
306       return wasm::ValType::F64;
307     if (Type == "v128" || Type == "i8x16" || Type == "i16x8" ||
308         Type == "i32x4" || Type == "i64x2" || Type == "f32x4" ||
309         Type == "f64x2")
310       return wasm::ValType::V128;
311     if (Type == "except_ref")
312       return wasm::ValType::EXCEPT_REF;
313     return Optional<wasm::ValType>();
314   }
315 
316   WebAssembly::ExprType parseBlockType(StringRef ID) {
317     return StringSwitch<WebAssembly::ExprType>(ID)
318         .Case("i32", WebAssembly::ExprType::I32)
319         .Case("i64", WebAssembly::ExprType::I64)
320         .Case("f32", WebAssembly::ExprType::F32)
321         .Case("f64", WebAssembly::ExprType::F64)
322         .Case("v128", WebAssembly::ExprType::V128)
323         .Case("except_ref", WebAssembly::ExprType::ExceptRef)
324         .Case("void", WebAssembly::ExprType::Void)
325         .Default(WebAssembly::ExprType::Invalid);
326   }
327 
328   bool parseRegTypeList(SmallVectorImpl<wasm::ValType> &Types) {
329     while (Lexer.is(AsmToken::Identifier)) {
330       auto Type = parseType(Lexer.getTok().getString());
331       if (!Type)
332         return error("unknown type: ", Lexer.getTok());
333       Types.push_back(Type.getValue());
334       Parser.Lex();
335       if (!isNext(AsmToken::Comma))
336         break;
337     }
338     return false;
339   }
340 
341   void parseSingleInteger(bool IsNegative, OperandVector &Operands) {
342     auto &Int = Lexer.getTok();
343     int64_t Val = Int.getIntVal();
344     if (IsNegative)
345       Val = -Val;
346     Operands.push_back(make_unique<WebAssemblyOperand>(
347         WebAssemblyOperand::Integer, Int.getLoc(), Int.getEndLoc(),
348         WebAssemblyOperand::IntOp{Val}));
349     Parser.Lex();
350   }
351 
352   bool parseSingleFloat(bool IsNegative, OperandVector &Operands) {
353     auto &Flt = Lexer.getTok();
354     double Val;
355     if (Flt.getString().getAsDouble(Val, false))
356       return error("Cannot parse real: ", Flt);
357     if (IsNegative)
358       Val = -Val;
359     Operands.push_back(make_unique<WebAssemblyOperand>(
360         WebAssemblyOperand::Float, Flt.getLoc(), Flt.getEndLoc(),
361         WebAssemblyOperand::FltOp{Val}));
362     Parser.Lex();
363     return false;
364   }
365 
366   bool checkForP2AlignIfLoadStore(OperandVector &Operands, StringRef InstName) {
367     // FIXME: there is probably a cleaner way to do this.
368     auto IsLoadStore = InstName.find(".load") != StringRef::npos ||
369                        InstName.find(".store") != StringRef::npos;
370     auto IsAtomic = InstName.find("atomic.") != StringRef::npos;
371     if (IsLoadStore || IsAtomic) {
372       // Parse load/store operands of the form: offset:p2align=align
373       if (IsLoadStore && isNext(AsmToken::Colon)) {
374         auto Id = expectIdent();
375         if (Id != "p2align")
376           return error("Expected p2align, instead got: " + Id);
377         if (expect(AsmToken::Equal, "="))
378           return true;
379         if (!Lexer.is(AsmToken::Integer))
380           return error("Expected integer constant");
381         parseSingleInteger(false, Operands);
382       } else {
383         // Alignment not specified (or atomics, must use default alignment).
384         // We can't just call WebAssembly::GetDefaultP2Align since we don't have
385         // an opcode until after the assembly matcher, so set a default to fix
386         // up later.
387         auto Tok = Lexer.getTok();
388         Operands.push_back(make_unique<WebAssemblyOperand>(
389             WebAssemblyOperand::Integer, Tok.getLoc(), Tok.getEndLoc(),
390             WebAssemblyOperand::IntOp{-1}));
391       }
392     }
393     return false;
394   }
395 
396   void addBlockTypeOperand(OperandVector &Operands, SMLoc NameLoc,
397                            WebAssembly::ExprType BT) {
398     Operands.push_back(make_unique<WebAssemblyOperand>(
399         WebAssemblyOperand::Integer, NameLoc, NameLoc,
400         WebAssemblyOperand::IntOp{static_cast<int64_t>(BT)}));
401   }
402 
403   bool ParseInstruction(ParseInstructionInfo & /*Info*/, StringRef Name,
404                         SMLoc NameLoc, OperandVector &Operands) override {
405     // Note: Name does NOT point into the sourcecode, but to a local, so
406     // use NameLoc instead.
407     Name = StringRef(NameLoc.getPointer(), Name.size());
408 
409     // WebAssembly has instructions with / in them, which AsmLexer parses
410     // as seperate tokens, so if we find such tokens immediately adjacent (no
411     // whitespace), expand the name to include them:
412     for (;;) {
413       auto &Sep = Lexer.getTok();
414       if (Sep.getLoc().getPointer() != Name.end() ||
415           Sep.getKind() != AsmToken::Slash)
416         break;
417       // Extend name with /
418       Name = StringRef(Name.begin(), Name.size() + Sep.getString().size());
419       Parser.Lex();
420       // We must now find another identifier, or error.
421       auto &Id = Lexer.getTok();
422       if (Id.getKind() != AsmToken::Identifier ||
423           Id.getLoc().getPointer() != Name.end())
424         return error("Incomplete instruction name: ", Id);
425       Name = StringRef(Name.begin(), Name.size() + Id.getString().size());
426       Parser.Lex();
427     }
428 
429     // Now construct the name as first operand.
430     Operands.push_back(make_unique<WebAssemblyOperand>(
431         WebAssemblyOperand::Token, NameLoc, SMLoc::getFromPointer(Name.end()),
432         WebAssemblyOperand::TokOp{Name}));
433 
434     // If this instruction is part of a control flow structure, ensure
435     // proper nesting.
436     bool ExpectBlockType = false;
437     if (Name == "block") {
438       push(Block);
439       ExpectBlockType = true;
440     } else if (Name == "loop") {
441       push(Loop);
442       ExpectBlockType = true;
443     } else if (Name == "try") {
444       push(Try);
445       ExpectBlockType = true;
446     } else if (Name == "if") {
447       push(If);
448       ExpectBlockType = true;
449     } else if (Name == "else") {
450       if (pop(Name, If))
451         return true;
452       push(Else);
453     } else if (Name == "catch") {
454       if (pop(Name, Try))
455         return true;
456       push(Try);
457     } else if (Name == "end_if") {
458       if (pop(Name, If, Else))
459         return true;
460     } else if (Name == "end_try") {
461       if (pop(Name, Try))
462         return true;
463     } else if (Name == "end_loop") {
464       if (pop(Name, Loop))
465         return true;
466     } else if (Name == "end_block") {
467       if (pop(Name, Block))
468         return true;
469     } else if (Name == "end_function") {
470       CurrentState = EndFunction;
471       if (pop(Name, Function) || ensureEmptyNestingStack())
472         return true;
473     }
474 
475     while (Lexer.isNot(AsmToken::EndOfStatement)) {
476       auto &Tok = Lexer.getTok();
477       switch (Tok.getKind()) {
478       case AsmToken::Identifier: {
479         auto &Id = Lexer.getTok();
480         if (ExpectBlockType) {
481           // Assume this identifier is a block_type.
482           auto BT = parseBlockType(Id.getString());
483           if (BT == WebAssembly::ExprType::Invalid)
484             return error("Unknown block type: ", Id);
485           addBlockTypeOperand(Operands, NameLoc, BT);
486           Parser.Lex();
487         } else {
488           // Assume this identifier is a label.
489           const MCExpr *Val;
490           SMLoc End;
491           if (Parser.parseExpression(Val, End))
492             return error("Cannot parse symbol: ", Lexer.getTok());
493           Operands.push_back(make_unique<WebAssemblyOperand>(
494               WebAssemblyOperand::Symbol, Id.getLoc(), Id.getEndLoc(),
495               WebAssemblyOperand::SymOp{Val}));
496           if (checkForP2AlignIfLoadStore(Operands, Name))
497             return true;
498         }
499         break;
500       }
501       case AsmToken::Minus:
502         Parser.Lex();
503         if (Lexer.is(AsmToken::Integer)) {
504           parseSingleInteger(true, Operands);
505           if (checkForP2AlignIfLoadStore(Operands, Name))
506             return true;
507         } else if(Lexer.is(AsmToken::Real)) {
508           if (parseSingleFloat(true, Operands))
509             return true;
510         } else {
511           return error("Expected numeric constant instead got: ",
512                        Lexer.getTok());
513         }
514         break;
515       case AsmToken::Integer:
516         parseSingleInteger(false, Operands);
517         if (checkForP2AlignIfLoadStore(Operands, Name))
518           return true;
519         break;
520       case AsmToken::Real: {
521         if (parseSingleFloat(false, Operands))
522           return true;
523         break;
524       }
525       case AsmToken::LCurly: {
526         Parser.Lex();
527         auto Op = make_unique<WebAssemblyOperand>(
528             WebAssemblyOperand::BrList, Tok.getLoc(), Tok.getEndLoc());
529         if (!Lexer.is(AsmToken::RCurly))
530           for (;;) {
531             Op->BrL.List.push_back(Lexer.getTok().getIntVal());
532             expect(AsmToken::Integer, "integer");
533             if (!isNext(AsmToken::Comma))
534               break;
535           }
536         expect(AsmToken::RCurly, "}");
537         Operands.push_back(std::move(Op));
538         break;
539       }
540       default:
541         return error("Unexpected token in operand: ", Tok);
542       }
543       if (Lexer.isNot(AsmToken::EndOfStatement)) {
544         if (expect(AsmToken::Comma, ","))
545           return true;
546       }
547     }
548     if (ExpectBlockType && Operands.size() == 1) {
549       // Support blocks with no operands as default to void.
550       addBlockTypeOperand(Operands, NameLoc, WebAssembly::ExprType::Void);
551     }
552     Parser.Lex();
553     return false;
554   }
555 
556   void onLabelParsed(MCSymbol *Symbol) override {
557     LastLabel = Symbol;
558     CurrentState = Label;
559   }
560 
561   bool parseSignature(wasm::WasmSignature *Signature) {
562     if (expect(AsmToken::LParen, "("))
563       return true;
564     if (parseRegTypeList(Signature->Params))
565       return true;
566     if (expect(AsmToken::RParen, ")"))
567       return true;
568     if (expect(AsmToken::MinusGreater, "->"))
569       return true;
570     if (expect(AsmToken::LParen, "("))
571       return true;
572     if (parseRegTypeList(Signature->Returns))
573       return true;
574     if (expect(AsmToken::RParen, ")"))
575       return true;
576     return false;
577   }
578 
579   bool CheckDataSection() {
580     if (CurrentState != DataSection) {
581       auto WS = cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
582       if (WS && WS->getKind().isText())
583         return error("data directive must occur in a data segment: ",
584                      Lexer.getTok());
585     }
586     CurrentState = DataSection;
587     return false;
588   }
589 
590   // This function processes wasm-specific directives streamed to
591   // WebAssemblyTargetStreamer, all others go to the generic parser
592   // (see WasmAsmParser).
593   bool ParseDirective(AsmToken DirectiveID) override {
594     // This function has a really weird return value behavior that is different
595     // from all the other parsing functions:
596     // - return true && no tokens consumed -> don't know this directive / let
597     //   the generic parser handle it.
598     // - return true && tokens consumed -> a parsing error occurred.
599     // - return false -> processed this directive successfully.
600     assert(DirectiveID.getKind() == AsmToken::Identifier);
601     auto &Out = getStreamer();
602     auto &TOut =
603         reinterpret_cast<WebAssemblyTargetStreamer &>(*Out.getTargetStreamer());
604     auto &Ctx = Out.getContext();
605 
606     // TODO: any time we return an error, at least one token must have been
607     // consumed, otherwise this will not signal an error to the caller.
608     if (DirectiveID.getString() == ".globaltype") {
609       auto SymName = expectIdent();
610       if (SymName.empty())
611         return true;
612       if (expect(AsmToken::Comma, ","))
613         return true;
614       auto TypeTok = Lexer.getTok();
615       auto TypeName = expectIdent();
616       if (TypeName.empty())
617         return true;
618       auto Type = parseType(TypeName);
619       if (!Type)
620         return error("Unknown type in .globaltype directive: ", TypeTok);
621       // Now set this symbol with the correct type.
622       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
623       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
624       WasmSym->setGlobalType(
625           wasm::WasmGlobalType{uint8_t(Type.getValue()), true});
626       // And emit the directive again.
627       TOut.emitGlobalType(WasmSym);
628       return expect(AsmToken::EndOfStatement, "EOL");
629     }
630 
631     if (DirectiveID.getString() == ".functype") {
632       // This code has to send things to the streamer similar to
633       // WebAssemblyAsmPrinter::EmitFunctionBodyStart.
634       // TODO: would be good to factor this into a common function, but the
635       // assembler and backend really don't share any common code, and this code
636       // parses the locals seperately.
637       auto SymName = expectIdent();
638       if (SymName.empty())
639         return true;
640       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
641       if (CurrentState == Label && WasmSym == LastLabel) {
642         // This .functype indicates a start of a function.
643         if (ensureEmptyNestingStack())
644           return true;
645         CurrentState = FunctionStart;
646         LastFunctionLabel = LastLabel;
647         push(Function);
648       }
649       auto Signature = make_unique<wasm::WasmSignature>();
650       if (parseSignature(Signature.get()))
651         return true;
652       WasmSym->setSignature(Signature.get());
653       addSignature(std::move(Signature));
654       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
655       TOut.emitFunctionType(WasmSym);
656       // TODO: backend also calls TOut.emitIndIdx, but that is not implemented.
657       return expect(AsmToken::EndOfStatement, "EOL");
658     }
659 
660     if (DirectiveID.getString() == ".eventtype") {
661       auto SymName = expectIdent();
662       if (SymName.empty())
663         return true;
664       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
665       auto Signature = make_unique<wasm::WasmSignature>();
666       if (parseRegTypeList(Signature->Params))
667         return true;
668       WasmSym->setSignature(Signature.get());
669       addSignature(std::move(Signature));
670       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_EVENT);
671       TOut.emitEventType(WasmSym);
672       // TODO: backend also calls TOut.emitIndIdx, but that is not implemented.
673       return expect(AsmToken::EndOfStatement, "EOL");
674     }
675 
676     if (DirectiveID.getString() == ".local") {
677       if (CurrentState != FunctionStart)
678         return error(".local directive should follow the start of a function",
679                      Lexer.getTok());
680       SmallVector<wasm::ValType, 4> Locals;
681       if (parseRegTypeList(Locals))
682         return true;
683       TOut.emitLocal(Locals);
684       CurrentState = FunctionLocals;
685       return expect(AsmToken::EndOfStatement, "EOL");
686     }
687 
688     if (DirectiveID.getString() == ".int8" ||
689         DirectiveID.getString() == ".int16" ||
690         DirectiveID.getString() == ".int32" ||
691         DirectiveID.getString() == ".int64") {
692       if (CheckDataSection()) return true;
693       const MCExpr *Val;
694       SMLoc End;
695       if (Parser.parseExpression(Val, End))
696         return error("Cannot parse .int expression: ", Lexer.getTok());
697       size_t NumBits = 0;
698       DirectiveID.getString().drop_front(4).getAsInteger(10, NumBits);
699       Out.EmitValue(Val, NumBits / 8, End);
700       return expect(AsmToken::EndOfStatement, "EOL");
701     }
702 
703     if (DirectiveID.getString() == ".asciz") {
704       if (CheckDataSection()) return true;
705       std::string S;
706       if (Parser.parseEscapedString(S))
707         return error("Cannot parse string constant: ", Lexer.getTok());
708       Out.EmitBytes(StringRef(S.c_str(), S.length() + 1));
709       return expect(AsmToken::EndOfStatement, "EOL");
710     }
711 
712     return true; // We didn't process this directive.
713   }
714 
715   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned & /*Opcode*/,
716                                OperandVector &Operands, MCStreamer &Out,
717                                uint64_t &ErrorInfo,
718                                bool MatchingInlineAsm) override {
719     MCInst Inst;
720     unsigned MatchResult =
721         MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
722     switch (MatchResult) {
723     case Match_Success: {
724       if (CurrentState == FunctionStart) {
725         // This is the first instruction in a function, but we haven't seen
726         // a .local directive yet. The streamer requires locals to be encoded
727         // as a prelude to the instructions, so emit an empty list of locals
728         // here.
729         auto &TOut = reinterpret_cast<WebAssemblyTargetStreamer &>(
730             *Out.getTargetStreamer());
731         TOut.emitLocal(SmallVector<wasm::ValType, 0>());
732       }
733       // Fix unknown p2align operands.
734       auto Align = WebAssembly::GetDefaultP2AlignAny(Inst.getOpcode());
735       if (Align != -1U) {
736         auto &Op0 = Inst.getOperand(0);
737         if (Op0.getImm() == -1)
738           Op0.setImm(Align);
739       }
740       Out.EmitInstruction(Inst, getSTI());
741       if (CurrentState == EndFunction) {
742         onEndOfFunction();
743       } else {
744         CurrentState = Instructions;
745       }
746       return false;
747     }
748     case Match_MissingFeature:
749       return Parser.Error(
750           IDLoc, "instruction requires a WASM feature not currently enabled");
751     case Match_MnemonicFail:
752       return Parser.Error(IDLoc, "invalid instruction");
753     case Match_NearMisses:
754       return Parser.Error(IDLoc, "ambiguous instruction");
755     case Match_InvalidTiedOperand:
756     case Match_InvalidOperand: {
757       SMLoc ErrorLoc = IDLoc;
758       if (ErrorInfo != ~0ULL) {
759         if (ErrorInfo >= Operands.size())
760           return Parser.Error(IDLoc, "too few operands for instruction");
761         ErrorLoc = Operands[ErrorInfo]->getStartLoc();
762         if (ErrorLoc == SMLoc())
763           ErrorLoc = IDLoc;
764       }
765       return Parser.Error(ErrorLoc, "invalid operand for instruction");
766     }
767     }
768     llvm_unreachable("Implement any new match types added!");
769   }
770 
771   void doBeforeLabelEmit(MCSymbol *Symbol) override {
772     // Start a new section for the next function automatically, since our
773     // object writer expects each function to have its own section. This way
774     // The user can't forget this "convention".
775     auto SymName = Symbol->getName();
776     if (SymName.startswith(".L"))
777       return; // Local Symbol.
778     // Only create a new text section if we're already in one.
779     auto CWS = cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
780     if (!CWS || !CWS->getKind().isText())
781       return;
782     auto SecName = ".text." + SymName;
783     auto WS = getContext().getWasmSection(SecName, SectionKind::getText());
784     getStreamer().SwitchSection(WS);
785   }
786 
787   void onEndOfFunction() {
788     // Automatically output a .size directive, so it becomes optional for the
789     // user.
790     if (!LastFunctionLabel) return;
791     auto TempSym = getContext().createLinkerPrivateTempSymbol();
792     getStreamer().EmitLabel(TempSym);
793     auto Start = MCSymbolRefExpr::create(LastFunctionLabel, getContext());
794     auto End = MCSymbolRefExpr::create(TempSym, getContext());
795     auto Expr =
796         MCBinaryExpr::create(MCBinaryExpr::Sub, End, Start, getContext());
797     getStreamer().emitELFSize(LastFunctionLabel, Expr);
798   }
799 
800   void onEndOfFile() override { ensureEmptyNestingStack(); }
801 };
802 } // end anonymous namespace
803 
804 // Force static initialization.
805 extern "C" void LLVMInitializeWebAssemblyAsmParser() {
806   RegisterMCAsmParser<WebAssemblyAsmParser> X(getTheWebAssemblyTarget32());
807   RegisterMCAsmParser<WebAssemblyAsmParser> Y(getTheWebAssemblyTarget64());
808 }
809 
810 #define GET_REGISTER_MATCHER
811 #define GET_MATCHER_IMPLEMENTATION
812 #include "WebAssemblyGenAsmMatcher.inc"
813