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