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