xref: /freebsd/contrib/llvm-project/llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmParser.cpp (revision 77013d11e6483b970af25e13c9b892075742f7e5)
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 static const char *getSubtargetFeatureName(uint64_t Val);
39 
40 namespace {
41 
42 /// WebAssemblyOperand - Instances of this class represent the operands in a
43 /// parsed Wasm machine instruction.
44 struct WebAssemblyOperand : public MCParsedAsmOperand {
45   enum KindTy { Token, Integer, Float, Symbol, BrList } Kind;
46 
47   SMLoc StartLoc, EndLoc;
48 
49   struct TokOp {
50     StringRef Tok;
51   };
52 
53   struct IntOp {
54     int64_t Val;
55   };
56 
57   struct FltOp {
58     double Val;
59   };
60 
61   struct SymOp {
62     const MCExpr *Exp;
63   };
64 
65   struct BrLOp {
66     std::vector<unsigned> List;
67   };
68 
69   union {
70     struct TokOp Tok;
71     struct IntOp Int;
72     struct FltOp Flt;
73     struct SymOp Sym;
74     struct BrLOp BrL;
75   };
76 
77   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, TokOp T)
78       : Kind(K), StartLoc(Start), EndLoc(End), Tok(T) {}
79   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, IntOp I)
80       : Kind(K), StartLoc(Start), EndLoc(End), Int(I) {}
81   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, FltOp F)
82       : Kind(K), StartLoc(Start), EndLoc(End), Flt(F) {}
83   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, SymOp S)
84       : Kind(K), StartLoc(Start), EndLoc(End), Sym(S) {}
85   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End)
86       : Kind(K), StartLoc(Start), EndLoc(End), BrL() {}
87 
88   ~WebAssemblyOperand() {
89     if (isBrList())
90       BrL.~BrLOp();
91   }
92 
93   bool isToken() const override { return Kind == Token; }
94   bool isImm() const override { return Kind == Integer || Kind == Symbol; }
95   bool isFPImm() const { return Kind == Float; }
96   bool isMem() const override { return false; }
97   bool isReg() const override { return false; }
98   bool isBrList() const { return Kind == BrList; }
99 
100   unsigned getReg() const override {
101     llvm_unreachable("Assembly inspects a register operand");
102     return 0;
103   }
104 
105   StringRef getToken() const {
106     assert(isToken());
107     return Tok.Tok;
108   }
109 
110   SMLoc getStartLoc() const override { return StartLoc; }
111   SMLoc getEndLoc() const override { return EndLoc; }
112 
113   void addRegOperands(MCInst &, unsigned) const {
114     // Required by the assembly matcher.
115     llvm_unreachable("Assembly matcher creates register operands");
116   }
117 
118   void addImmOperands(MCInst &Inst, unsigned N) const {
119     assert(N == 1 && "Invalid number of operands!");
120     if (Kind == Integer)
121       Inst.addOperand(MCOperand::createImm(Int.Val));
122     else if (Kind == Symbol)
123       Inst.addOperand(MCOperand::createExpr(Sym.Exp));
124     else
125       llvm_unreachable("Should be integer immediate or symbol!");
126   }
127 
128   void addFPImmOperands(MCInst &Inst, unsigned N) const {
129     assert(N == 1 && "Invalid number of operands!");
130     if (Kind == Float)
131       Inst.addOperand(MCOperand::createFPImm(Flt.Val));
132     else
133       llvm_unreachable("Should be float immediate!");
134   }
135 
136   void addBrListOperands(MCInst &Inst, unsigned N) const {
137     assert(N == 1 && isBrList() && "Invalid BrList!");
138     for (auto Br : BrL.List)
139       Inst.addOperand(MCOperand::createImm(Br));
140   }
141 
142   void print(raw_ostream &OS) const override {
143     switch (Kind) {
144     case Token:
145       OS << "Tok:" << Tok.Tok;
146       break;
147     case Integer:
148       OS << "Int:" << Int.Val;
149       break;
150     case Float:
151       OS << "Flt:" << Flt.Val;
152       break;
153     case Symbol:
154       OS << "Sym:" << Sym.Exp;
155       break;
156     case BrList:
157       OS << "BrList:" << BrL.List.size();
158       break;
159     }
160   }
161 };
162 
163 static MCSymbolWasm *GetOrCreateFunctionTableSymbol(MCContext &Ctx,
164                                                     const StringRef &Name) {
165   // FIXME: Duplicates functionality from
166   // MC/WasmObjectWriter::recordRelocation, as well as WebAssemblyCodegen's
167   // WebAssembly:getOrCreateFunctionTableSymbol.
168   MCSymbolWasm *Sym = cast_or_null<MCSymbolWasm>(Ctx.lookupSymbol(Name));
169   if (Sym) {
170     if (!Sym->isFunctionTable())
171       Ctx.reportError(SMLoc(), "symbol is not a wasm funcref table");
172   } else {
173     Sym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(Name));
174     Sym->setFunctionTable();
175     // The default function table is synthesized by the linker.
176     Sym->setUndefined();
177   }
178   return Sym;
179 }
180 
181 class WebAssemblyAsmParser final : public MCTargetAsmParser {
182   MCAsmParser &Parser;
183   MCAsmLexer &Lexer;
184 
185   // Much like WebAssemblyAsmPrinter in the backend, we have to own these.
186   std::vector<std::unique_ptr<wasm::WasmSignature>> Signatures;
187   std::vector<std::unique_ptr<std::string>> Names;
188 
189   // Order of labels, directives and instructions in a .s file have no
190   // syntactical enforcement. This class is a callback from the actual parser,
191   // and yet we have to be feeding data to the streamer in a very particular
192   // order to ensure a correct binary encoding that matches the regular backend
193   // (the streamer does not enforce this). This "state machine" enum helps
194   // guarantee that correct order.
195   enum ParserState {
196     FileStart,
197     Label,
198     FunctionStart,
199     FunctionLocals,
200     Instructions,
201     EndFunction,
202     DataSection,
203   } CurrentState = FileStart;
204 
205   // For ensuring blocks are properly nested.
206   enum NestingType {
207     Function,
208     Block,
209     Loop,
210     Try,
211     If,
212     Else,
213     Undefined,
214   };
215   std::vector<NestingType> NestingStack;
216 
217   // We track this to see if a .functype following a label is the same,
218   // as this is how we recognize the start of a function.
219   MCSymbol *LastLabel = nullptr;
220   MCSymbol *LastFunctionLabel = nullptr;
221 
222 public:
223   WebAssemblyAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
224                        const MCInstrInfo &MII, const MCTargetOptions &Options)
225       : MCTargetAsmParser(Options, STI, MII), Parser(Parser),
226         Lexer(Parser.getLexer()) {
227     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
228   }
229 
230 #define GET_ASSEMBLER_HEADER
231 #include "WebAssemblyGenAsmMatcher.inc"
232 
233   // TODO: This is required to be implemented, but appears unused.
234   bool ParseRegister(unsigned & /*RegNo*/, SMLoc & /*StartLoc*/,
235                      SMLoc & /*EndLoc*/) override {
236     llvm_unreachable("ParseRegister is not implemented.");
237   }
238   OperandMatchResultTy tryParseRegister(unsigned & /*RegNo*/,
239                                         SMLoc & /*StartLoc*/,
240                                         SMLoc & /*EndLoc*/) override {
241     llvm_unreachable("tryParseRegister is not implemented.");
242   }
243 
244   bool error(const Twine &Msg, const AsmToken &Tok) {
245     return Parser.Error(Tok.getLoc(), Msg + Tok.getString());
246   }
247 
248   bool error(const Twine &Msg) {
249     return Parser.Error(Lexer.getTok().getLoc(), Msg);
250   }
251 
252   void addSignature(std::unique_ptr<wasm::WasmSignature> &&Sig) {
253     Signatures.push_back(std::move(Sig));
254   }
255 
256   StringRef storeName(StringRef Name) {
257     std::unique_ptr<std::string> N = std::make_unique<std::string>(Name);
258     Names.push_back(std::move(N));
259     return *Names.back();
260   }
261 
262   std::pair<StringRef, StringRef> nestingString(NestingType NT) {
263     switch (NT) {
264     case Function:
265       return {"function", "end_function"};
266     case Block:
267       return {"block", "end_block"};
268     case Loop:
269       return {"loop", "end_loop"};
270     case Try:
271       return {"try", "end_try"};
272     case If:
273       return {"if", "end_if"};
274     case Else:
275       return {"else", "end_if"};
276     default:
277       llvm_unreachable("unknown NestingType");
278     }
279   }
280 
281   void push(NestingType NT) { NestingStack.push_back(NT); }
282 
283   bool pop(StringRef Ins, NestingType NT1, NestingType NT2 = Undefined) {
284     if (NestingStack.empty())
285       return error(Twine("End of block construct with no start: ") + Ins);
286     auto Top = NestingStack.back();
287     if (Top != NT1 && Top != NT2)
288       return error(Twine("Block construct type mismatch, expected: ") +
289                    nestingString(Top).second + ", instead got: " + Ins);
290     NestingStack.pop_back();
291     return false;
292   }
293 
294   bool ensureEmptyNestingStack() {
295     auto Err = !NestingStack.empty();
296     while (!NestingStack.empty()) {
297       error(Twine("Unmatched block construct(s) at function end: ") +
298             nestingString(NestingStack.back()).first);
299       NestingStack.pop_back();
300     }
301     return Err;
302   }
303 
304   bool isNext(AsmToken::TokenKind Kind) {
305     auto Ok = Lexer.is(Kind);
306     if (Ok)
307       Parser.Lex();
308     return Ok;
309   }
310 
311   bool expect(AsmToken::TokenKind Kind, const char *KindName) {
312     if (!isNext(Kind))
313       return error(std::string("Expected ") + KindName + ", instead got: ",
314                    Lexer.getTok());
315     return false;
316   }
317 
318   StringRef expectIdent() {
319     if (!Lexer.is(AsmToken::Identifier)) {
320       error("Expected identifier, got: ", Lexer.getTok());
321       return StringRef();
322     }
323     auto Name = Lexer.getTok().getString();
324     Parser.Lex();
325     return Name;
326   }
327 
328   Optional<wasm::ValType> parseType(const StringRef &Type) {
329     // FIXME: can't use StringSwitch because wasm::ValType doesn't have a
330     // "invalid" value.
331     if (Type == "i32")
332       return wasm::ValType::I32;
333     if (Type == "i64")
334       return wasm::ValType::I64;
335     if (Type == "f32")
336       return wasm::ValType::F32;
337     if (Type == "f64")
338       return wasm::ValType::F64;
339     if (Type == "v128" || Type == "i8x16" || Type == "i16x8" ||
340         Type == "i32x4" || Type == "i64x2" || Type == "f32x4" ||
341         Type == "f64x2")
342       return wasm::ValType::V128;
343     if (Type == "funcref")
344       return wasm::ValType::FUNCREF;
345     if (Type == "externref")
346       return wasm::ValType::EXTERNREF;
347     return Optional<wasm::ValType>();
348   }
349 
350   WebAssembly::BlockType parseBlockType(StringRef ID) {
351     // Multivalue block types are handled separately in parseSignature
352     return StringSwitch<WebAssembly::BlockType>(ID)
353         .Case("i32", WebAssembly::BlockType::I32)
354         .Case("i64", WebAssembly::BlockType::I64)
355         .Case("f32", WebAssembly::BlockType::F32)
356         .Case("f64", WebAssembly::BlockType::F64)
357         .Case("v128", WebAssembly::BlockType::V128)
358         .Case("funcref", WebAssembly::BlockType::Funcref)
359         .Case("externref", WebAssembly::BlockType::Externref)
360         .Case("void", WebAssembly::BlockType::Void)
361         .Default(WebAssembly::BlockType::Invalid);
362   }
363 
364   bool parseRegTypeList(SmallVectorImpl<wasm::ValType> &Types) {
365     while (Lexer.is(AsmToken::Identifier)) {
366       auto Type = parseType(Lexer.getTok().getString());
367       if (!Type)
368         return error("unknown type: ", Lexer.getTok());
369       Types.push_back(Type.getValue());
370       Parser.Lex();
371       if (!isNext(AsmToken::Comma))
372         break;
373     }
374     return false;
375   }
376 
377   void parseSingleInteger(bool IsNegative, OperandVector &Operands) {
378     auto &Int = Lexer.getTok();
379     int64_t Val = Int.getIntVal();
380     if (IsNegative)
381       Val = -Val;
382     Operands.push_back(std::make_unique<WebAssemblyOperand>(
383         WebAssemblyOperand::Integer, Int.getLoc(), Int.getEndLoc(),
384         WebAssemblyOperand::IntOp{Val}));
385     Parser.Lex();
386   }
387 
388   bool parseSingleFloat(bool IsNegative, OperandVector &Operands) {
389     auto &Flt = Lexer.getTok();
390     double Val;
391     if (Flt.getString().getAsDouble(Val, false))
392       return error("Cannot parse real: ", Flt);
393     if (IsNegative)
394       Val = -Val;
395     Operands.push_back(std::make_unique<WebAssemblyOperand>(
396         WebAssemblyOperand::Float, Flt.getLoc(), Flt.getEndLoc(),
397         WebAssemblyOperand::FltOp{Val}));
398     Parser.Lex();
399     return false;
400   }
401 
402   bool parseSpecialFloatMaybe(bool IsNegative, OperandVector &Operands) {
403     if (Lexer.isNot(AsmToken::Identifier))
404       return true;
405     auto &Flt = Lexer.getTok();
406     auto S = Flt.getString();
407     double Val;
408     if (S.compare_lower("infinity") == 0) {
409       Val = std::numeric_limits<double>::infinity();
410     } else if (S.compare_lower("nan") == 0) {
411       Val = std::numeric_limits<double>::quiet_NaN();
412     } else {
413       return true;
414     }
415     if (IsNegative)
416       Val = -Val;
417     Operands.push_back(std::make_unique<WebAssemblyOperand>(
418         WebAssemblyOperand::Float, Flt.getLoc(), Flt.getEndLoc(),
419         WebAssemblyOperand::FltOp{Val}));
420     Parser.Lex();
421     return false;
422   }
423 
424   bool checkForP2AlignIfLoadStore(OperandVector &Operands, StringRef InstName) {
425     // FIXME: there is probably a cleaner way to do this.
426     auto IsLoadStore = InstName.find(".load") != StringRef::npos ||
427                        InstName.find(".store") != StringRef::npos ||
428                        InstName.find("prefetch") != StringRef::npos;
429     auto IsAtomic = InstName.find("atomic.") != StringRef::npos;
430     if (IsLoadStore || IsAtomic) {
431       // Parse load/store operands of the form: offset:p2align=align
432       if (IsLoadStore && isNext(AsmToken::Colon)) {
433         auto Id = expectIdent();
434         if (Id != "p2align")
435           return error("Expected p2align, instead got: " + Id);
436         if (expect(AsmToken::Equal, "="))
437           return true;
438         if (!Lexer.is(AsmToken::Integer))
439           return error("Expected integer constant");
440         parseSingleInteger(false, Operands);
441       } else {
442         // v128.{load,store}{8,16,32,64}_lane has both a memarg and a lane
443         // index. We need to avoid parsing an extra alignment operand for the
444         // lane index.
445         auto IsLoadStoreLane = InstName.find("_lane") != StringRef::npos;
446         if (IsLoadStoreLane && Operands.size() == 4)
447           return false;
448         // Alignment not specified (or atomics, must use default alignment).
449         // We can't just call WebAssembly::GetDefaultP2Align since we don't have
450         // an opcode until after the assembly matcher, so set a default to fix
451         // up later.
452         auto Tok = Lexer.getTok();
453         Operands.push_back(std::make_unique<WebAssemblyOperand>(
454             WebAssemblyOperand::Integer, Tok.getLoc(), Tok.getEndLoc(),
455             WebAssemblyOperand::IntOp{-1}));
456       }
457     }
458     return false;
459   }
460 
461   WebAssembly::HeapType parseHeapType(StringRef Id) {
462     return StringSwitch<WebAssembly::HeapType>(Id)
463         .Case("extern", WebAssembly::HeapType::Externref)
464         .Case("func", WebAssembly::HeapType::Funcref)
465         .Default(WebAssembly::HeapType::Invalid);
466   }
467 
468   void addBlockTypeOperand(OperandVector &Operands, SMLoc NameLoc,
469                            WebAssembly::BlockType BT) {
470     Operands.push_back(std::make_unique<WebAssemblyOperand>(
471         WebAssemblyOperand::Integer, NameLoc, NameLoc,
472         WebAssemblyOperand::IntOp{static_cast<int64_t>(BT)}));
473   }
474 
475   bool ParseInstruction(ParseInstructionInfo & /*Info*/, StringRef Name,
476                         SMLoc NameLoc, OperandVector &Operands) override {
477     // Note: Name does NOT point into the sourcecode, but to a local, so
478     // use NameLoc instead.
479     Name = StringRef(NameLoc.getPointer(), Name.size());
480 
481     // WebAssembly has instructions with / in them, which AsmLexer parses
482     // as separate tokens, so if we find such tokens immediately adjacent (no
483     // whitespace), expand the name to include them:
484     for (;;) {
485       auto &Sep = Lexer.getTok();
486       if (Sep.getLoc().getPointer() != Name.end() ||
487           Sep.getKind() != AsmToken::Slash)
488         break;
489       // Extend name with /
490       Name = StringRef(Name.begin(), Name.size() + Sep.getString().size());
491       Parser.Lex();
492       // We must now find another identifier, or error.
493       auto &Id = Lexer.getTok();
494       if (Id.getKind() != AsmToken::Identifier ||
495           Id.getLoc().getPointer() != Name.end())
496         return error("Incomplete instruction name: ", Id);
497       Name = StringRef(Name.begin(), Name.size() + Id.getString().size());
498       Parser.Lex();
499     }
500 
501     // Now construct the name as first operand.
502     Operands.push_back(std::make_unique<WebAssemblyOperand>(
503         WebAssemblyOperand::Token, NameLoc, SMLoc::getFromPointer(Name.end()),
504         WebAssemblyOperand::TokOp{Name}));
505 
506     // If this instruction is part of a control flow structure, ensure
507     // proper nesting.
508     bool ExpectBlockType = false;
509     bool ExpectFuncType = false;
510     bool ExpectHeapType = false;
511     if (Name == "block") {
512       push(Block);
513       ExpectBlockType = true;
514     } else if (Name == "loop") {
515       push(Loop);
516       ExpectBlockType = true;
517     } else if (Name == "try") {
518       push(Try);
519       ExpectBlockType = true;
520     } else if (Name == "if") {
521       push(If);
522       ExpectBlockType = true;
523     } else if (Name == "else") {
524       if (pop(Name, If))
525         return true;
526       push(Else);
527     } else if (Name == "catch") {
528       if (pop(Name, Try))
529         return true;
530       push(Try);
531     } else if (Name == "end_if") {
532       if (pop(Name, If, Else))
533         return true;
534     } else if (Name == "end_try") {
535       if (pop(Name, Try))
536         return true;
537     } else if (Name == "end_loop") {
538       if (pop(Name, Loop))
539         return true;
540     } else if (Name == "end_block") {
541       if (pop(Name, Block))
542         return true;
543     } else if (Name == "end_function") {
544       ensureLocals(getStreamer());
545       CurrentState = EndFunction;
546       if (pop(Name, Function) || ensureEmptyNestingStack())
547         return true;
548     } else if (Name == "call_indirect" || Name == "return_call_indirect") {
549       ExpectFuncType = true;
550       // Ensure that the object file has a __indirect_function_table import, as
551       // we call_indirect against it.
552       auto &Ctx = getStreamer().getContext();
553       MCSymbolWasm *Sym =
554           GetOrCreateFunctionTableSymbol(Ctx, "__indirect_function_table");
555       // Until call_indirect emits TABLE_NUMBER relocs against this symbol, mark
556       // it as NO_STRIP so as to ensure that the indirect function table makes
557       // it to linked output.
558       Sym->setNoStrip();
559     } else if (Name == "ref.null") {
560       ExpectHeapType = true;
561     }
562 
563     if (ExpectFuncType || (ExpectBlockType && Lexer.is(AsmToken::LParen))) {
564       // This has a special TYPEINDEX operand which in text we
565       // represent as a signature, such that we can re-build this signature,
566       // attach it to an anonymous symbol, which is what WasmObjectWriter
567       // expects to be able to recreate the actual unique-ified type indices.
568       auto Loc = Parser.getTok();
569       auto Signature = std::make_unique<wasm::WasmSignature>();
570       if (parseSignature(Signature.get()))
571         return true;
572       // Got signature as block type, don't need more
573       ExpectBlockType = false;
574       auto &Ctx = getStreamer().getContext();
575       // The "true" here will cause this to be a nameless symbol.
576       MCSymbol *Sym = Ctx.createTempSymbol("typeindex", true);
577       auto *WasmSym = cast<MCSymbolWasm>(Sym);
578       WasmSym->setSignature(Signature.get());
579       addSignature(std::move(Signature));
580       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
581       const MCExpr *Expr = MCSymbolRefExpr::create(
582           WasmSym, MCSymbolRefExpr::VK_WASM_TYPEINDEX, Ctx);
583       Operands.push_back(std::make_unique<WebAssemblyOperand>(
584           WebAssemblyOperand::Symbol, Loc.getLoc(), Loc.getEndLoc(),
585           WebAssemblyOperand::SymOp{Expr}));
586     }
587 
588     while (Lexer.isNot(AsmToken::EndOfStatement)) {
589       auto &Tok = Lexer.getTok();
590       switch (Tok.getKind()) {
591       case AsmToken::Identifier: {
592         if (!parseSpecialFloatMaybe(false, Operands))
593           break;
594         auto &Id = Lexer.getTok();
595         if (ExpectBlockType) {
596           // Assume this identifier is a block_type.
597           auto BT = parseBlockType(Id.getString());
598           if (BT == WebAssembly::BlockType::Invalid)
599             return error("Unknown block type: ", Id);
600           addBlockTypeOperand(Operands, NameLoc, BT);
601           Parser.Lex();
602         } else if (ExpectHeapType) {
603           auto HeapType = parseHeapType(Id.getString());
604           if (HeapType == WebAssembly::HeapType::Invalid) {
605             return error("Expected a heap type: ", Id);
606           }
607           Operands.push_back(std::make_unique<WebAssemblyOperand>(
608               WebAssemblyOperand::Integer, Id.getLoc(), Id.getEndLoc(),
609               WebAssemblyOperand::IntOp{static_cast<int64_t>(HeapType)}));
610           Parser.Lex();
611         } else {
612           // Assume this identifier is a label.
613           const MCExpr *Val;
614           SMLoc End;
615           if (Parser.parseExpression(Val, End))
616             return error("Cannot parse symbol: ", Lexer.getTok());
617           Operands.push_back(std::make_unique<WebAssemblyOperand>(
618               WebAssemblyOperand::Symbol, Id.getLoc(), Id.getEndLoc(),
619               WebAssemblyOperand::SymOp{Val}));
620           if (checkForP2AlignIfLoadStore(Operands, Name))
621             return true;
622         }
623         break;
624       }
625       case AsmToken::Minus:
626         Parser.Lex();
627         if (Lexer.is(AsmToken::Integer)) {
628           parseSingleInteger(true, Operands);
629           if (checkForP2AlignIfLoadStore(Operands, Name))
630             return true;
631         } else if(Lexer.is(AsmToken::Real)) {
632           if (parseSingleFloat(true, Operands))
633             return true;
634         } else if (!parseSpecialFloatMaybe(true, Operands)) {
635         } else {
636           return error("Expected numeric constant instead got: ",
637                        Lexer.getTok());
638         }
639         break;
640       case AsmToken::Integer:
641         parseSingleInteger(false, Operands);
642         if (checkForP2AlignIfLoadStore(Operands, Name))
643           return true;
644         break;
645       case AsmToken::Real: {
646         if (parseSingleFloat(false, Operands))
647           return true;
648         break;
649       }
650       case AsmToken::LCurly: {
651         Parser.Lex();
652         auto Op = std::make_unique<WebAssemblyOperand>(
653             WebAssemblyOperand::BrList, Tok.getLoc(), Tok.getEndLoc());
654         if (!Lexer.is(AsmToken::RCurly))
655           for (;;) {
656             Op->BrL.List.push_back(Lexer.getTok().getIntVal());
657             expect(AsmToken::Integer, "integer");
658             if (!isNext(AsmToken::Comma))
659               break;
660           }
661         expect(AsmToken::RCurly, "}");
662         Operands.push_back(std::move(Op));
663         break;
664       }
665       default:
666         return error("Unexpected token in operand: ", Tok);
667       }
668       if (Lexer.isNot(AsmToken::EndOfStatement)) {
669         if (expect(AsmToken::Comma, ","))
670           return true;
671       }
672     }
673     if (ExpectBlockType && Operands.size() == 1) {
674       // Support blocks with no operands as default to void.
675       addBlockTypeOperand(Operands, NameLoc, WebAssembly::BlockType::Void);
676     }
677     Parser.Lex();
678     return false;
679   }
680 
681   void onLabelParsed(MCSymbol *Symbol) override {
682     LastLabel = Symbol;
683     CurrentState = Label;
684   }
685 
686   bool parseSignature(wasm::WasmSignature *Signature) {
687     if (expect(AsmToken::LParen, "("))
688       return true;
689     if (parseRegTypeList(Signature->Params))
690       return true;
691     if (expect(AsmToken::RParen, ")"))
692       return true;
693     if (expect(AsmToken::MinusGreater, "->"))
694       return true;
695     if (expect(AsmToken::LParen, "("))
696       return true;
697     if (parseRegTypeList(Signature->Returns))
698       return true;
699     if (expect(AsmToken::RParen, ")"))
700       return true;
701     return false;
702   }
703 
704   bool CheckDataSection() {
705     if (CurrentState != DataSection) {
706       auto WS = cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
707       if (WS && WS->getKind().isText())
708         return error("data directive must occur in a data segment: ",
709                      Lexer.getTok());
710     }
711     CurrentState = DataSection;
712     return false;
713   }
714 
715   // This function processes wasm-specific directives streamed to
716   // WebAssemblyTargetStreamer, all others go to the generic parser
717   // (see WasmAsmParser).
718   bool ParseDirective(AsmToken DirectiveID) override {
719     // This function has a really weird return value behavior that is different
720     // from all the other parsing functions:
721     // - return true && no tokens consumed -> don't know this directive / let
722     //   the generic parser handle it.
723     // - return true && tokens consumed -> a parsing error occurred.
724     // - return false -> processed this directive successfully.
725     assert(DirectiveID.getKind() == AsmToken::Identifier);
726     auto &Out = getStreamer();
727     auto &TOut =
728         reinterpret_cast<WebAssemblyTargetStreamer &>(*Out.getTargetStreamer());
729     auto &Ctx = Out.getContext();
730 
731     // TODO: any time we return an error, at least one token must have been
732     // consumed, otherwise this will not signal an error to the caller.
733     if (DirectiveID.getString() == ".globaltype") {
734       auto SymName = expectIdent();
735       if (SymName.empty())
736         return true;
737       if (expect(AsmToken::Comma, ","))
738         return true;
739       auto TypeTok = Lexer.getTok();
740       auto TypeName = expectIdent();
741       if (TypeName.empty())
742         return true;
743       auto Type = parseType(TypeName);
744       if (!Type)
745         return error("Unknown type in .globaltype directive: ", TypeTok);
746       // Optional mutable modifier. Default to mutable for historical reasons.
747       // Ideally we would have gone with immutable as the default and used `mut`
748       // as the modifier to match the `.wat` format.
749       bool Mutable = true;
750       if (isNext(AsmToken::Comma)) {
751         TypeTok = Lexer.getTok();
752         auto Id = expectIdent();
753         if (Id == "immutable")
754           Mutable = false;
755         else
756           // Should we also allow `mutable` and `mut` here for clarity?
757           return error("Unknown type in .globaltype modifier: ", TypeTok);
758       }
759       // Now set this symbol with the correct type.
760       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
761       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
762       WasmSym->setGlobalType(
763           wasm::WasmGlobalType{uint8_t(Type.getValue()), Mutable});
764       // And emit the directive again.
765       TOut.emitGlobalType(WasmSym);
766       return expect(AsmToken::EndOfStatement, "EOL");
767     }
768 
769     if (DirectiveID.getString() == ".tabletype") {
770       auto SymName = expectIdent();
771       if (SymName.empty())
772         return true;
773       if (expect(AsmToken::Comma, ","))
774         return true;
775       auto TypeTok = Lexer.getTok();
776       auto TypeName = expectIdent();
777       if (TypeName.empty())
778         return true;
779       auto Type = parseType(TypeName);
780       if (!Type)
781         return error("Unknown type in .tabletype directive: ", TypeTok);
782 
783       // Now that we have the name and table type, we can actually create the
784       // symbol
785       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
786       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TABLE);
787       WasmSym->setTableType(Type.getValue());
788       TOut.emitTableType(WasmSym);
789       return expect(AsmToken::EndOfStatement, "EOL");
790     }
791 
792     if (DirectiveID.getString() == ".functype") {
793       // This code has to send things to the streamer similar to
794       // WebAssemblyAsmPrinter::EmitFunctionBodyStart.
795       // TODO: would be good to factor this into a common function, but the
796       // assembler and backend really don't share any common code, and this code
797       // parses the locals separately.
798       auto SymName = expectIdent();
799       if (SymName.empty())
800         return true;
801       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
802       if (CurrentState == Label && WasmSym == LastLabel) {
803         // This .functype indicates a start of a function.
804         if (ensureEmptyNestingStack())
805           return true;
806         CurrentState = FunctionStart;
807         LastFunctionLabel = LastLabel;
808         push(Function);
809       }
810       auto Signature = std::make_unique<wasm::WasmSignature>();
811       if (parseSignature(Signature.get()))
812         return true;
813       WasmSym->setSignature(Signature.get());
814       addSignature(std::move(Signature));
815       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
816       TOut.emitFunctionType(WasmSym);
817       // TODO: backend also calls TOut.emitIndIdx, but that is not implemented.
818       return expect(AsmToken::EndOfStatement, "EOL");
819     }
820 
821     if (DirectiveID.getString() == ".export_name") {
822       auto SymName = expectIdent();
823       if (SymName.empty())
824         return true;
825       if (expect(AsmToken::Comma, ","))
826         return true;
827       auto ExportName = expectIdent();
828       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
829       WasmSym->setExportName(storeName(ExportName));
830       TOut.emitExportName(WasmSym, ExportName);
831     }
832 
833     if (DirectiveID.getString() == ".import_module") {
834       auto SymName = expectIdent();
835       if (SymName.empty())
836         return true;
837       if (expect(AsmToken::Comma, ","))
838         return true;
839       auto ImportModule = expectIdent();
840       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
841       WasmSym->setImportModule(storeName(ImportModule));
842       TOut.emitImportModule(WasmSym, ImportModule);
843     }
844 
845     if (DirectiveID.getString() == ".import_name") {
846       auto SymName = expectIdent();
847       if (SymName.empty())
848         return true;
849       if (expect(AsmToken::Comma, ","))
850         return true;
851       auto ImportName = expectIdent();
852       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
853       WasmSym->setImportName(storeName(ImportName));
854       TOut.emitImportName(WasmSym, ImportName);
855     }
856 
857     if (DirectiveID.getString() == ".eventtype") {
858       auto SymName = expectIdent();
859       if (SymName.empty())
860         return true;
861       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
862       auto Signature = std::make_unique<wasm::WasmSignature>();
863       if (parseRegTypeList(Signature->Params))
864         return true;
865       WasmSym->setSignature(Signature.get());
866       addSignature(std::move(Signature));
867       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_EVENT);
868       TOut.emitEventType(WasmSym);
869       // TODO: backend also calls TOut.emitIndIdx, but that is not implemented.
870       return expect(AsmToken::EndOfStatement, "EOL");
871     }
872 
873     if (DirectiveID.getString() == ".local") {
874       if (CurrentState != FunctionStart)
875         return error(".local directive should follow the start of a function",
876                      Lexer.getTok());
877       SmallVector<wasm::ValType, 4> Locals;
878       if (parseRegTypeList(Locals))
879         return true;
880       TOut.emitLocal(Locals);
881       CurrentState = FunctionLocals;
882       return expect(AsmToken::EndOfStatement, "EOL");
883     }
884 
885     if (DirectiveID.getString() == ".int8" ||
886         DirectiveID.getString() == ".int16" ||
887         DirectiveID.getString() == ".int32" ||
888         DirectiveID.getString() == ".int64") {
889       if (CheckDataSection()) return true;
890       const MCExpr *Val;
891       SMLoc End;
892       if (Parser.parseExpression(Val, End))
893         return error("Cannot parse .int expression: ", Lexer.getTok());
894       size_t NumBits = 0;
895       DirectiveID.getString().drop_front(4).getAsInteger(10, NumBits);
896       Out.emitValue(Val, NumBits / 8, End);
897       return expect(AsmToken::EndOfStatement, "EOL");
898     }
899 
900     if (DirectiveID.getString() == ".asciz") {
901       if (CheckDataSection()) return true;
902       std::string S;
903       if (Parser.parseEscapedString(S))
904         return error("Cannot parse string constant: ", Lexer.getTok());
905       Out.emitBytes(StringRef(S.c_str(), S.length() + 1));
906       return expect(AsmToken::EndOfStatement, "EOL");
907     }
908 
909     return true; // We didn't process this directive.
910   }
911 
912   // Called either when the first instruction is parsed of the function ends.
913   void ensureLocals(MCStreamer &Out) {
914     if (CurrentState == FunctionStart) {
915       // We haven't seen a .local directive yet. The streamer requires locals to
916       // be encoded as a prelude to the instructions, so emit an empty list of
917       // locals here.
918       auto &TOut = reinterpret_cast<WebAssemblyTargetStreamer &>(
919           *Out.getTargetStreamer());
920       TOut.emitLocal(SmallVector<wasm::ValType, 0>());
921       CurrentState = FunctionLocals;
922     }
923   }
924 
925   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned & /*Opcode*/,
926                                OperandVector &Operands, MCStreamer &Out,
927                                uint64_t &ErrorInfo,
928                                bool MatchingInlineAsm) override {
929     MCInst Inst;
930     Inst.setLoc(IDLoc);
931     FeatureBitset MissingFeatures;
932     unsigned MatchResult = MatchInstructionImpl(
933         Operands, Inst, ErrorInfo, MissingFeatures, MatchingInlineAsm);
934     switch (MatchResult) {
935     case Match_Success: {
936       ensureLocals(Out);
937       // Fix unknown p2align operands.
938       auto Align = WebAssembly::GetDefaultP2AlignAny(Inst.getOpcode());
939       if (Align != -1U) {
940         auto &Op0 = Inst.getOperand(0);
941         if (Op0.getImm() == -1)
942           Op0.setImm(Align);
943       }
944       if (getSTI().getTargetTriple().isArch64Bit()) {
945         // Upgrade 32-bit loads/stores to 64-bit. These mostly differ by having
946         // an offset64 arg instead of offset32, but to the assembler matcher
947         // they're both immediates so don't get selected for.
948         auto Opc64 = WebAssembly::getWasm64Opcode(
949             static_cast<uint16_t>(Inst.getOpcode()));
950         if (Opc64 >= 0) {
951           Inst.setOpcode(Opc64);
952         }
953       }
954       Out.emitInstruction(Inst, getSTI());
955       if (CurrentState == EndFunction) {
956         onEndOfFunction();
957       } else {
958         CurrentState = Instructions;
959       }
960       return false;
961     }
962     case Match_MissingFeature: {
963       assert(MissingFeatures.count() > 0 && "Expected missing features");
964       SmallString<128> Message;
965       raw_svector_ostream OS(Message);
966       OS << "instruction requires:";
967       for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)
968         if (MissingFeatures.test(i))
969           OS << ' ' << getSubtargetFeatureName(i);
970       return Parser.Error(IDLoc, Message);
971     }
972     case Match_MnemonicFail:
973       return Parser.Error(IDLoc, "invalid instruction");
974     case Match_NearMisses:
975       return Parser.Error(IDLoc, "ambiguous instruction");
976     case Match_InvalidTiedOperand:
977     case Match_InvalidOperand: {
978       SMLoc ErrorLoc = IDLoc;
979       if (ErrorInfo != ~0ULL) {
980         if (ErrorInfo >= Operands.size())
981           return Parser.Error(IDLoc, "too few operands for instruction");
982         ErrorLoc = Operands[ErrorInfo]->getStartLoc();
983         if (ErrorLoc == SMLoc())
984           ErrorLoc = IDLoc;
985       }
986       return Parser.Error(ErrorLoc, "invalid operand for instruction");
987     }
988     }
989     llvm_unreachable("Implement any new match types added!");
990   }
991 
992   void doBeforeLabelEmit(MCSymbol *Symbol) override {
993     // Start a new section for the next function automatically, since our
994     // object writer expects each function to have its own section. This way
995     // The user can't forget this "convention".
996     auto SymName = Symbol->getName();
997     if (SymName.startswith(".L"))
998       return; // Local Symbol.
999 
1000     // Only create a new text section if we're already in one.
1001     // TODO: If the user explicitly creates a new function section, we ignore
1002     // its name when we create this one. It would be nice to honor their
1003     // choice, while still ensuring that we create one if they forget.
1004     // (that requires coordination with WasmAsmParser::parseSectionDirective)
1005     auto CWS = cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
1006     if (!CWS || !CWS->getKind().isText())
1007       return;
1008     auto SecName = ".text." + SymName;
1009 
1010     auto *Group = CWS->getGroup();
1011     // If the current section is a COMDAT, also set the flag on the symbol.
1012     // TODO: Currently the only place that the symbols' comdat flag matters is
1013     // for importing comdat functions. But there's no way to specify that in
1014     // assembly currently.
1015     if (Group)
1016       cast<MCSymbolWasm>(Symbol)->setComdat(true);
1017     auto *WS =
1018         getContext().getWasmSection(SecName, SectionKind::getText(), Group,
1019                                     MCContext::GenericSectionID, nullptr);
1020     getStreamer().SwitchSection(WS);
1021     // Also generate DWARF for this section if requested.
1022     if (getContext().getGenDwarfForAssembly())
1023       getContext().addGenDwarfSection(WS);
1024   }
1025 
1026   void onEndOfFunction() {
1027     // Automatically output a .size directive, so it becomes optional for the
1028     // user.
1029     if (!LastFunctionLabel) return;
1030     auto TempSym = getContext().createLinkerPrivateTempSymbol();
1031     getStreamer().emitLabel(TempSym);
1032     auto Start = MCSymbolRefExpr::create(LastFunctionLabel, getContext());
1033     auto End = MCSymbolRefExpr::create(TempSym, getContext());
1034     auto Expr =
1035         MCBinaryExpr::create(MCBinaryExpr::Sub, End, Start, getContext());
1036     getStreamer().emitELFSize(LastFunctionLabel, Expr);
1037   }
1038 
1039   void onEndOfFile() override { ensureEmptyNestingStack(); }
1040 };
1041 } // end anonymous namespace
1042 
1043 // Force static initialization.
1044 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyAsmParser() {
1045   RegisterMCAsmParser<WebAssemblyAsmParser> X(getTheWebAssemblyTarget32());
1046   RegisterMCAsmParser<WebAssemblyAsmParser> Y(getTheWebAssemblyTarget64());
1047 }
1048 
1049 #define GET_REGISTER_MATCHER
1050 #define GET_SUBTARGET_FEATURE_NAME
1051 #define GET_MATCHER_IMPLEMENTATION
1052 #include "WebAssemblyGenAsmMatcher.inc"
1053