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   OperandMatchResultTy tryParseRegister(unsigned & /*RegNo*/,
218                                         SMLoc & /*StartLoc*/,
219                                         SMLoc & /*EndLoc*/) override {
220     llvm_unreachable("tryParseRegister is not implemented.");
221   }
222 
223   bool error(const Twine &Msg, const AsmToken &Tok) {
224     return Parser.Error(Tok.getLoc(), Msg + Tok.getString());
225   }
226 
227   bool error(const Twine &Msg) {
228     return Parser.Error(Lexer.getTok().getLoc(), Msg);
229   }
230 
231   void addSignature(std::unique_ptr<wasm::WasmSignature> &&Sig) {
232     Signatures.push_back(std::move(Sig));
233   }
234 
235   std::pair<StringRef, StringRef> nestingString(NestingType NT) {
236     switch (NT) {
237     case Function:
238       return {"function", "end_function"};
239     case Block:
240       return {"block", "end_block"};
241     case Loop:
242       return {"loop", "end_loop"};
243     case Try:
244       return {"try", "end_try"};
245     case If:
246       return {"if", "end_if"};
247     case Else:
248       return {"else", "end_if"};
249     default:
250       llvm_unreachable("unknown NestingType");
251     }
252   }
253 
254   void push(NestingType NT) { NestingStack.push_back(NT); }
255 
256   bool pop(StringRef Ins, NestingType NT1, NestingType NT2 = Undefined) {
257     if (NestingStack.empty())
258       return error(Twine("End of block construct with no start: ") + Ins);
259     auto Top = NestingStack.back();
260     if (Top != NT1 && Top != NT2)
261       return error(Twine("Block construct type mismatch, expected: ") +
262                    nestingString(Top).second + ", instead got: " + Ins);
263     NestingStack.pop_back();
264     return false;
265   }
266 
267   bool ensureEmptyNestingStack() {
268     auto Err = !NestingStack.empty();
269     while (!NestingStack.empty()) {
270       error(Twine("Unmatched block construct(s) at function end: ") +
271             nestingString(NestingStack.back()).first);
272       NestingStack.pop_back();
273     }
274     return Err;
275   }
276 
277   bool isNext(AsmToken::TokenKind Kind) {
278     auto Ok = Lexer.is(Kind);
279     if (Ok)
280       Parser.Lex();
281     return Ok;
282   }
283 
284   bool expect(AsmToken::TokenKind Kind, const char *KindName) {
285     if (!isNext(Kind))
286       return error(std::string("Expected ") + KindName + ", instead got: ",
287                    Lexer.getTok());
288     return false;
289   }
290 
291   StringRef expectIdent() {
292     if (!Lexer.is(AsmToken::Identifier)) {
293       error("Expected identifier, got: ", Lexer.getTok());
294       return StringRef();
295     }
296     auto Name = Lexer.getTok().getString();
297     Parser.Lex();
298     return Name;
299   }
300 
301   Optional<wasm::ValType> parseType(const StringRef &Type) {
302     // FIXME: can't use StringSwitch because wasm::ValType doesn't have a
303     // "invalid" value.
304     if (Type == "i32")
305       return wasm::ValType::I32;
306     if (Type == "i64")
307       return wasm::ValType::I64;
308     if (Type == "f32")
309       return wasm::ValType::F32;
310     if (Type == "f64")
311       return wasm::ValType::F64;
312     if (Type == "v128" || Type == "i8x16" || Type == "i16x8" ||
313         Type == "i32x4" || Type == "i64x2" || Type == "f32x4" ||
314         Type == "f64x2")
315       return wasm::ValType::V128;
316     if (Type == "exnref")
317       return wasm::ValType::EXNREF;
318     return Optional<wasm::ValType>();
319   }
320 
321   WebAssembly::BlockType parseBlockType(StringRef ID) {
322     // Multivalue block types are handled separately in parseSignature
323     return StringSwitch<WebAssembly::BlockType>(ID)
324         .Case("i32", WebAssembly::BlockType::I32)
325         .Case("i64", WebAssembly::BlockType::I64)
326         .Case("f32", WebAssembly::BlockType::F32)
327         .Case("f64", WebAssembly::BlockType::F64)
328         .Case("v128", WebAssembly::BlockType::V128)
329         .Case("exnref", WebAssembly::BlockType::Exnref)
330         .Case("void", WebAssembly::BlockType::Void)
331         .Default(WebAssembly::BlockType::Invalid);
332   }
333 
334   bool parseRegTypeList(SmallVectorImpl<wasm::ValType> &Types) {
335     while (Lexer.is(AsmToken::Identifier)) {
336       auto Type = parseType(Lexer.getTok().getString());
337       if (!Type)
338         return error("unknown type: ", Lexer.getTok());
339       Types.push_back(Type.getValue());
340       Parser.Lex();
341       if (!isNext(AsmToken::Comma))
342         break;
343     }
344     return false;
345   }
346 
347   void parseSingleInteger(bool IsNegative, OperandVector &Operands) {
348     auto &Int = Lexer.getTok();
349     int64_t Val = Int.getIntVal();
350     if (IsNegative)
351       Val = -Val;
352     Operands.push_back(std::make_unique<WebAssemblyOperand>(
353         WebAssemblyOperand::Integer, Int.getLoc(), Int.getEndLoc(),
354         WebAssemblyOperand::IntOp{Val}));
355     Parser.Lex();
356   }
357 
358   bool parseSingleFloat(bool IsNegative, OperandVector &Operands) {
359     auto &Flt = Lexer.getTok();
360     double Val;
361     if (Flt.getString().getAsDouble(Val, false))
362       return error("Cannot parse real: ", Flt);
363     if (IsNegative)
364       Val = -Val;
365     Operands.push_back(std::make_unique<WebAssemblyOperand>(
366         WebAssemblyOperand::Float, Flt.getLoc(), Flt.getEndLoc(),
367         WebAssemblyOperand::FltOp{Val}));
368     Parser.Lex();
369     return false;
370   }
371 
372   bool parseSpecialFloatMaybe(bool IsNegative, OperandVector &Operands) {
373     if (Lexer.isNot(AsmToken::Identifier))
374       return true;
375     auto &Flt = Lexer.getTok();
376     auto S = Flt.getString();
377     double Val;
378     if (S.compare_lower("infinity") == 0) {
379       Val = std::numeric_limits<double>::infinity();
380     } else if (S.compare_lower("nan") == 0) {
381       Val = std::numeric_limits<double>::quiet_NaN();
382     } else {
383       return true;
384     }
385     if (IsNegative)
386       Val = -Val;
387     Operands.push_back(std::make_unique<WebAssemblyOperand>(
388         WebAssemblyOperand::Float, Flt.getLoc(), Flt.getEndLoc(),
389         WebAssemblyOperand::FltOp{Val}));
390     Parser.Lex();
391     return false;
392   }
393 
394   bool checkForP2AlignIfLoadStore(OperandVector &Operands, StringRef InstName) {
395     // FIXME: there is probably a cleaner way to do this.
396     auto IsLoadStore = InstName.find(".load") != StringRef::npos ||
397                        InstName.find(".store") != StringRef::npos;
398     auto IsAtomic = InstName.find("atomic.") != StringRef::npos;
399     if (IsLoadStore || IsAtomic) {
400       // Parse load/store operands of the form: offset:p2align=align
401       if (IsLoadStore && isNext(AsmToken::Colon)) {
402         auto Id = expectIdent();
403         if (Id != "p2align")
404           return error("Expected p2align, instead got: " + Id);
405         if (expect(AsmToken::Equal, "="))
406           return true;
407         if (!Lexer.is(AsmToken::Integer))
408           return error("Expected integer constant");
409         parseSingleInteger(false, Operands);
410       } else {
411         // Alignment not specified (or atomics, must use default alignment).
412         // We can't just call WebAssembly::GetDefaultP2Align since we don't have
413         // an opcode until after the assembly matcher, so set a default to fix
414         // up later.
415         auto Tok = Lexer.getTok();
416         Operands.push_back(std::make_unique<WebAssemblyOperand>(
417             WebAssemblyOperand::Integer, Tok.getLoc(), Tok.getEndLoc(),
418             WebAssemblyOperand::IntOp{-1}));
419       }
420     }
421     return false;
422   }
423 
424   void addBlockTypeOperand(OperandVector &Operands, SMLoc NameLoc,
425                            WebAssembly::BlockType BT) {
426     Operands.push_back(std::make_unique<WebAssemblyOperand>(
427         WebAssemblyOperand::Integer, NameLoc, NameLoc,
428         WebAssemblyOperand::IntOp{static_cast<int64_t>(BT)}));
429   }
430 
431   bool ParseInstruction(ParseInstructionInfo & /*Info*/, StringRef Name,
432                         SMLoc NameLoc, OperandVector &Operands) override {
433     // Note: Name does NOT point into the sourcecode, but to a local, so
434     // use NameLoc instead.
435     Name = StringRef(NameLoc.getPointer(), Name.size());
436 
437     // WebAssembly has instructions with / in them, which AsmLexer parses
438     // as seperate tokens, so if we find such tokens immediately adjacent (no
439     // whitespace), expand the name to include them:
440     for (;;) {
441       auto &Sep = Lexer.getTok();
442       if (Sep.getLoc().getPointer() != Name.end() ||
443           Sep.getKind() != AsmToken::Slash)
444         break;
445       // Extend name with /
446       Name = StringRef(Name.begin(), Name.size() + Sep.getString().size());
447       Parser.Lex();
448       // We must now find another identifier, or error.
449       auto &Id = Lexer.getTok();
450       if (Id.getKind() != AsmToken::Identifier ||
451           Id.getLoc().getPointer() != Name.end())
452         return error("Incomplete instruction name: ", Id);
453       Name = StringRef(Name.begin(), Name.size() + Id.getString().size());
454       Parser.Lex();
455     }
456 
457     // Now construct the name as first operand.
458     Operands.push_back(std::make_unique<WebAssemblyOperand>(
459         WebAssemblyOperand::Token, NameLoc, SMLoc::getFromPointer(Name.end()),
460         WebAssemblyOperand::TokOp{Name}));
461 
462     // If this instruction is part of a control flow structure, ensure
463     // proper nesting.
464     bool ExpectBlockType = false;
465     bool ExpectFuncType = false;
466     if (Name == "block") {
467       push(Block);
468       ExpectBlockType = true;
469     } else if (Name == "loop") {
470       push(Loop);
471       ExpectBlockType = true;
472     } else if (Name == "try") {
473       push(Try);
474       ExpectBlockType = true;
475     } else if (Name == "if") {
476       push(If);
477       ExpectBlockType = true;
478     } else if (Name == "else") {
479       if (pop(Name, If))
480         return true;
481       push(Else);
482     } else if (Name == "catch") {
483       if (pop(Name, Try))
484         return true;
485       push(Try);
486     } else if (Name == "end_if") {
487       if (pop(Name, If, Else))
488         return true;
489     } else if (Name == "end_try") {
490       if (pop(Name, Try))
491         return true;
492     } else if (Name == "end_loop") {
493       if (pop(Name, Loop))
494         return true;
495     } else if (Name == "end_block") {
496       if (pop(Name, Block))
497         return true;
498     } else if (Name == "end_function") {
499       ensureLocals(getStreamer());
500       CurrentState = EndFunction;
501       if (pop(Name, Function) || ensureEmptyNestingStack())
502         return true;
503     } else if (Name == "call_indirect" || Name == "return_call_indirect") {
504       ExpectFuncType = true;
505     }
506 
507     if (ExpectFuncType || (ExpectBlockType && Lexer.is(AsmToken::LParen))) {
508       // This has a special TYPEINDEX operand which in text we
509       // represent as a signature, such that we can re-build this signature,
510       // attach it to an anonymous symbol, which is what WasmObjectWriter
511       // expects to be able to recreate the actual unique-ified type indices.
512       auto Loc = Parser.getTok();
513       auto Signature = std::make_unique<wasm::WasmSignature>();
514       if (parseSignature(Signature.get()))
515         return true;
516       // Got signature as block type, don't need more
517       ExpectBlockType = false;
518       auto &Ctx = getStreamer().getContext();
519       // The "true" here will cause this to be a nameless symbol.
520       MCSymbol *Sym = Ctx.createTempSymbol("typeindex", true);
521       auto *WasmSym = cast<MCSymbolWasm>(Sym);
522       WasmSym->setSignature(Signature.get());
523       addSignature(std::move(Signature));
524       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
525       const MCExpr *Expr = MCSymbolRefExpr::create(
526           WasmSym, MCSymbolRefExpr::VK_WASM_TYPEINDEX, Ctx);
527       Operands.push_back(std::make_unique<WebAssemblyOperand>(
528           WebAssemblyOperand::Symbol, Loc.getLoc(), Loc.getEndLoc(),
529           WebAssemblyOperand::SymOp{Expr}));
530     }
531 
532     while (Lexer.isNot(AsmToken::EndOfStatement)) {
533       auto &Tok = Lexer.getTok();
534       switch (Tok.getKind()) {
535       case AsmToken::Identifier: {
536         if (!parseSpecialFloatMaybe(false, Operands))
537           break;
538         auto &Id = Lexer.getTok();
539         if (ExpectBlockType) {
540           // Assume this identifier is a block_type.
541           auto BT = parseBlockType(Id.getString());
542           if (BT == WebAssembly::BlockType::Invalid)
543             return error("Unknown block type: ", Id);
544           addBlockTypeOperand(Operands, NameLoc, BT);
545           Parser.Lex();
546         } else {
547           // Assume this identifier is a label.
548           const MCExpr *Val;
549           SMLoc End;
550           if (Parser.parseExpression(Val, End))
551             return error("Cannot parse symbol: ", Lexer.getTok());
552           Operands.push_back(std::make_unique<WebAssemblyOperand>(
553               WebAssemblyOperand::Symbol, Id.getLoc(), Id.getEndLoc(),
554               WebAssemblyOperand::SymOp{Val}));
555           if (checkForP2AlignIfLoadStore(Operands, Name))
556             return true;
557         }
558         break;
559       }
560       case AsmToken::Minus:
561         Parser.Lex();
562         if (Lexer.is(AsmToken::Integer)) {
563           parseSingleInteger(true, Operands);
564           if (checkForP2AlignIfLoadStore(Operands, Name))
565             return true;
566         } else if(Lexer.is(AsmToken::Real)) {
567           if (parseSingleFloat(true, Operands))
568             return true;
569         } else if (!parseSpecialFloatMaybe(true, Operands)) {
570         } else {
571           return error("Expected numeric constant instead got: ",
572                        Lexer.getTok());
573         }
574         break;
575       case AsmToken::Integer:
576         parseSingleInteger(false, Operands);
577         if (checkForP2AlignIfLoadStore(Operands, Name))
578           return true;
579         break;
580       case AsmToken::Real: {
581         if (parseSingleFloat(false, Operands))
582           return true;
583         break;
584       }
585       case AsmToken::LCurly: {
586         Parser.Lex();
587         auto Op = std::make_unique<WebAssemblyOperand>(
588             WebAssemblyOperand::BrList, Tok.getLoc(), Tok.getEndLoc());
589         if (!Lexer.is(AsmToken::RCurly))
590           for (;;) {
591             Op->BrL.List.push_back(Lexer.getTok().getIntVal());
592             expect(AsmToken::Integer, "integer");
593             if (!isNext(AsmToken::Comma))
594               break;
595           }
596         expect(AsmToken::RCurly, "}");
597         Operands.push_back(std::move(Op));
598         break;
599       }
600       default:
601         return error("Unexpected token in operand: ", Tok);
602       }
603       if (Lexer.isNot(AsmToken::EndOfStatement)) {
604         if (expect(AsmToken::Comma, ","))
605           return true;
606       }
607     }
608     if (ExpectBlockType && Operands.size() == 1) {
609       // Support blocks with no operands as default to void.
610       addBlockTypeOperand(Operands, NameLoc, WebAssembly::BlockType::Void);
611     }
612     Parser.Lex();
613     return false;
614   }
615 
616   void onLabelParsed(MCSymbol *Symbol) override {
617     LastLabel = Symbol;
618     CurrentState = Label;
619   }
620 
621   bool parseSignature(wasm::WasmSignature *Signature) {
622     if (expect(AsmToken::LParen, "("))
623       return true;
624     if (parseRegTypeList(Signature->Params))
625       return true;
626     if (expect(AsmToken::RParen, ")"))
627       return true;
628     if (expect(AsmToken::MinusGreater, "->"))
629       return true;
630     if (expect(AsmToken::LParen, "("))
631       return true;
632     if (parseRegTypeList(Signature->Returns))
633       return true;
634     if (expect(AsmToken::RParen, ")"))
635       return true;
636     return false;
637   }
638 
639   bool CheckDataSection() {
640     if (CurrentState != DataSection) {
641       auto WS = cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
642       if (WS && WS->getKind().isText())
643         return error("data directive must occur in a data segment: ",
644                      Lexer.getTok());
645     }
646     CurrentState = DataSection;
647     return false;
648   }
649 
650   // This function processes wasm-specific directives streamed to
651   // WebAssemblyTargetStreamer, all others go to the generic parser
652   // (see WasmAsmParser).
653   bool ParseDirective(AsmToken DirectiveID) override {
654     // This function has a really weird return value behavior that is different
655     // from all the other parsing functions:
656     // - return true && no tokens consumed -> don't know this directive / let
657     //   the generic parser handle it.
658     // - return true && tokens consumed -> a parsing error occurred.
659     // - return false -> processed this directive successfully.
660     assert(DirectiveID.getKind() == AsmToken::Identifier);
661     auto &Out = getStreamer();
662     auto &TOut =
663         reinterpret_cast<WebAssemblyTargetStreamer &>(*Out.getTargetStreamer());
664     auto &Ctx = Out.getContext();
665 
666     // TODO: any time we return an error, at least one token must have been
667     // consumed, otherwise this will not signal an error to the caller.
668     if (DirectiveID.getString() == ".globaltype") {
669       auto SymName = expectIdent();
670       if (SymName.empty())
671         return true;
672       if (expect(AsmToken::Comma, ","))
673         return true;
674       auto TypeTok = Lexer.getTok();
675       auto TypeName = expectIdent();
676       if (TypeName.empty())
677         return true;
678       auto Type = parseType(TypeName);
679       if (!Type)
680         return error("Unknown type in .globaltype directive: ", TypeTok);
681       // Now set this symbol with the correct type.
682       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
683       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
684       WasmSym->setGlobalType(
685           wasm::WasmGlobalType{uint8_t(Type.getValue()), true});
686       // And emit the directive again.
687       TOut.emitGlobalType(WasmSym);
688       return expect(AsmToken::EndOfStatement, "EOL");
689     }
690 
691     if (DirectiveID.getString() == ".functype") {
692       // This code has to send things to the streamer similar to
693       // WebAssemblyAsmPrinter::EmitFunctionBodyStart.
694       // TODO: would be good to factor this into a common function, but the
695       // assembler and backend really don't share any common code, and this code
696       // parses the locals seperately.
697       auto SymName = expectIdent();
698       if (SymName.empty())
699         return true;
700       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
701       if (CurrentState == Label && WasmSym == LastLabel) {
702         // This .functype indicates a start of a function.
703         if (ensureEmptyNestingStack())
704           return true;
705         CurrentState = FunctionStart;
706         LastFunctionLabel = LastLabel;
707         push(Function);
708       }
709       auto Signature = std::make_unique<wasm::WasmSignature>();
710       if (parseSignature(Signature.get()))
711         return true;
712       WasmSym->setSignature(Signature.get());
713       addSignature(std::move(Signature));
714       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
715       TOut.emitFunctionType(WasmSym);
716       // TODO: backend also calls TOut.emitIndIdx, but that is not implemented.
717       return expect(AsmToken::EndOfStatement, "EOL");
718     }
719 
720     if (DirectiveID.getString() == ".export_name") {
721       auto SymName = expectIdent();
722       if (SymName.empty())
723         return true;
724       if (expect(AsmToken::Comma, ","))
725         return true;
726       auto ExportName = expectIdent();
727       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
728       WasmSym->setExportName(ExportName);
729       TOut.emitExportName(WasmSym, ExportName);
730     }
731 
732     if (DirectiveID.getString() == ".import_module") {
733       auto SymName = expectIdent();
734       if (SymName.empty())
735         return true;
736       if (expect(AsmToken::Comma, ","))
737         return true;
738       auto ImportModule = expectIdent();
739       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
740       WasmSym->setImportModule(ImportModule);
741       TOut.emitImportModule(WasmSym, ImportModule);
742     }
743 
744     if (DirectiveID.getString() == ".import_name") {
745       auto SymName = expectIdent();
746       if (SymName.empty())
747         return true;
748       if (expect(AsmToken::Comma, ","))
749         return true;
750       auto ImportName = expectIdent();
751       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
752       WasmSym->setImportName(ImportName);
753       TOut.emitImportName(WasmSym, ImportName);
754     }
755 
756     if (DirectiveID.getString() == ".eventtype") {
757       auto SymName = expectIdent();
758       if (SymName.empty())
759         return true;
760       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
761       auto Signature = std::make_unique<wasm::WasmSignature>();
762       if (parseRegTypeList(Signature->Params))
763         return true;
764       WasmSym->setSignature(Signature.get());
765       addSignature(std::move(Signature));
766       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_EVENT);
767       TOut.emitEventType(WasmSym);
768       // TODO: backend also calls TOut.emitIndIdx, but that is not implemented.
769       return expect(AsmToken::EndOfStatement, "EOL");
770     }
771 
772     if (DirectiveID.getString() == ".local") {
773       if (CurrentState != FunctionStart)
774         return error(".local directive should follow the start of a function",
775                      Lexer.getTok());
776       SmallVector<wasm::ValType, 4> Locals;
777       if (parseRegTypeList(Locals))
778         return true;
779       TOut.emitLocal(Locals);
780       CurrentState = FunctionLocals;
781       return expect(AsmToken::EndOfStatement, "EOL");
782     }
783 
784     if (DirectiveID.getString() == ".int8" ||
785         DirectiveID.getString() == ".int16" ||
786         DirectiveID.getString() == ".int32" ||
787         DirectiveID.getString() == ".int64") {
788       if (CheckDataSection()) return true;
789       const MCExpr *Val;
790       SMLoc End;
791       if (Parser.parseExpression(Val, End))
792         return error("Cannot parse .int expression: ", Lexer.getTok());
793       size_t NumBits = 0;
794       DirectiveID.getString().drop_front(4).getAsInteger(10, NumBits);
795       Out.emitValue(Val, NumBits / 8, End);
796       return expect(AsmToken::EndOfStatement, "EOL");
797     }
798 
799     if (DirectiveID.getString() == ".asciz") {
800       if (CheckDataSection()) return true;
801       std::string S;
802       if (Parser.parseEscapedString(S))
803         return error("Cannot parse string constant: ", Lexer.getTok());
804       Out.emitBytes(StringRef(S.c_str(), S.length() + 1));
805       return expect(AsmToken::EndOfStatement, "EOL");
806     }
807 
808     return true; // We didn't process this directive.
809   }
810 
811   // Called either when the first instruction is parsed of the function ends.
812   void ensureLocals(MCStreamer &Out) {
813     if (CurrentState == FunctionStart) {
814       // We haven't seen a .local directive yet. The streamer requires locals to
815       // be encoded as a prelude to the instructions, so emit an empty list of
816       // locals here.
817       auto &TOut = reinterpret_cast<WebAssemblyTargetStreamer &>(
818           *Out.getTargetStreamer());
819       TOut.emitLocal(SmallVector<wasm::ValType, 0>());
820       CurrentState = FunctionLocals;
821     }
822   }
823 
824   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned & /*Opcode*/,
825                                OperandVector &Operands, MCStreamer &Out,
826                                uint64_t &ErrorInfo,
827                                bool MatchingInlineAsm) override {
828     MCInst Inst;
829     Inst.setLoc(IDLoc);
830     unsigned MatchResult =
831         MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
832     switch (MatchResult) {
833     case Match_Success: {
834       ensureLocals(Out);
835       // Fix unknown p2align operands.
836       auto Align = WebAssembly::GetDefaultP2AlignAny(Inst.getOpcode());
837       if (Align != -1U) {
838         auto &Op0 = Inst.getOperand(0);
839         if (Op0.getImm() == -1)
840           Op0.setImm(Align);
841       }
842       Out.emitInstruction(Inst, getSTI());
843       if (CurrentState == EndFunction) {
844         onEndOfFunction();
845       } else {
846         CurrentState = Instructions;
847       }
848       return false;
849     }
850     case Match_MissingFeature:
851       return Parser.Error(
852           IDLoc, "instruction requires a WASM feature not currently enabled");
853     case Match_MnemonicFail:
854       return Parser.Error(IDLoc, "invalid instruction");
855     case Match_NearMisses:
856       return Parser.Error(IDLoc, "ambiguous instruction");
857     case Match_InvalidTiedOperand:
858     case Match_InvalidOperand: {
859       SMLoc ErrorLoc = IDLoc;
860       if (ErrorInfo != ~0ULL) {
861         if (ErrorInfo >= Operands.size())
862           return Parser.Error(IDLoc, "too few operands for instruction");
863         ErrorLoc = Operands[ErrorInfo]->getStartLoc();
864         if (ErrorLoc == SMLoc())
865           ErrorLoc = IDLoc;
866       }
867       return Parser.Error(ErrorLoc, "invalid operand for instruction");
868     }
869     }
870     llvm_unreachable("Implement any new match types added!");
871   }
872 
873   void doBeforeLabelEmit(MCSymbol *Symbol) override {
874     // Start a new section for the next function automatically, since our
875     // object writer expects each function to have its own section. This way
876     // The user can't forget this "convention".
877     auto SymName = Symbol->getName();
878     if (SymName.startswith(".L"))
879       return; // Local Symbol.
880     // Only create a new text section if we're already in one.
881     auto CWS = cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
882     if (!CWS || !CWS->getKind().isText())
883       return;
884     auto SecName = ".text." + SymName;
885     auto WS = getContext().getWasmSection(SecName, SectionKind::getText());
886     getStreamer().SwitchSection(WS);
887     // Also generate DWARF for this section if requested.
888     if (getContext().getGenDwarfForAssembly())
889       getContext().addGenDwarfSection(WS);
890   }
891 
892   void onEndOfFunction() {
893     // Automatically output a .size directive, so it becomes optional for the
894     // user.
895     if (!LastFunctionLabel) return;
896     auto TempSym = getContext().createLinkerPrivateTempSymbol();
897     getStreamer().emitLabel(TempSym);
898     auto Start = MCSymbolRefExpr::create(LastFunctionLabel, getContext());
899     auto End = MCSymbolRefExpr::create(TempSym, getContext());
900     auto Expr =
901         MCBinaryExpr::create(MCBinaryExpr::Sub, End, Start, getContext());
902     getStreamer().emitELFSize(LastFunctionLabel, Expr);
903   }
904 
905   void onEndOfFile() override { ensureEmptyNestingStack(); }
906 };
907 } // end anonymous namespace
908 
909 // Force static initialization.
910 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyAsmParser() {
911   RegisterMCAsmParser<WebAssemblyAsmParser> X(getTheWebAssemblyTarget32());
912   RegisterMCAsmParser<WebAssemblyAsmParser> Y(getTheWebAssemblyTarget64());
913 }
914 
915 #define GET_REGISTER_MATCHER
916 #define GET_MATCHER_IMPLEMENTATION
917 #include "WebAssemblyGenAsmMatcher.inc"
918