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