xref: /llvm-project/llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmParser.cpp (revision defb8fb2c67f1f5052f236f2eefeae028c0b3f15)
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 "AsmParser/WebAssemblyAsmTypeCheck.h"
17 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
18 #include "MCTargetDesc/WebAssemblyMCTypeUtilities.h"
19 #include "MCTargetDesc/WebAssemblyTargetStreamer.h"
20 #include "TargetInfo/WebAssemblyTargetInfo.h"
21 #include "WebAssembly.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCInst.h"
25 #include "llvm/MC/MCInstrInfo.h"
26 #include "llvm/MC/MCParser/MCAsmLexer.h"
27 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
28 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
29 #include "llvm/MC/MCSectionWasm.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/MC/MCSymbolWasm.h"
34 #include "llvm/MC/TargetRegistry.h"
35 #include "llvm/Support/SourceMgr.h"
36 
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "wasm-asm-parser"
40 
41 static const char *getSubtargetFeatureName(uint64_t Val);
42 
43 namespace {
44 
45 /// WebAssemblyOperand - Instances of this class represent the operands in a
46 /// parsed Wasm machine instruction.
47 struct WebAssemblyOperand : public MCParsedAsmOperand {
48   enum KindTy { Token, Integer, Float, Symbol, BrList, CatchList } Kind;
49 
50   SMLoc StartLoc, EndLoc;
51 
52   struct TokOp {
53     StringRef Tok;
54   };
55 
56   struct IntOp {
57     int64_t Val;
58   };
59 
60   struct FltOp {
61     double Val;
62   };
63 
64   struct SymOp {
65     const MCExpr *Exp;
66   };
67 
68   struct BrLOp {
69     std::vector<unsigned> List;
70   };
71 
72   struct CaLOpElem {
73     uint8_t Opcode;
74     const MCExpr *Tag;
75     unsigned Dest;
76   };
77 
78   struct CaLOp {
79     std::vector<CaLOpElem> List;
80   };
81 
82   union {
83     struct TokOp Tok;
84     struct IntOp Int;
85     struct FltOp Flt;
86     struct SymOp Sym;
87     struct BrLOp BrL;
88     struct CaLOp CaL;
89   };
90 
91   WebAssemblyOperand(SMLoc Start, SMLoc End, TokOp T)
92       : Kind(Token), StartLoc(Start), EndLoc(End), Tok(T) {}
93   WebAssemblyOperand(SMLoc Start, SMLoc End, IntOp I)
94       : Kind(Integer), StartLoc(Start), EndLoc(End), Int(I) {}
95   WebAssemblyOperand(SMLoc Start, SMLoc End, FltOp F)
96       : Kind(Float), StartLoc(Start), EndLoc(End), Flt(F) {}
97   WebAssemblyOperand(SMLoc Start, SMLoc End, SymOp S)
98       : Kind(Symbol), StartLoc(Start), EndLoc(End), Sym(S) {}
99   WebAssemblyOperand(SMLoc Start, SMLoc End, BrLOp B)
100       : Kind(BrList), StartLoc(Start), EndLoc(End), BrL(B) {}
101   WebAssemblyOperand(SMLoc Start, SMLoc End, CaLOp C)
102       : Kind(CatchList), StartLoc(Start), EndLoc(End), CaL(C) {}
103 
104   ~WebAssemblyOperand() {
105     if (isBrList())
106       BrL.~BrLOp();
107     if (isCatchList())
108       CaL.~CaLOp();
109   }
110 
111   bool isToken() const override { return Kind == Token; }
112   bool isImm() const override { return Kind == Integer || Kind == Symbol; }
113   bool isFPImm() const { return Kind == Float; }
114   bool isMem() const override { return false; }
115   bool isReg() const override { return false; }
116   bool isBrList() const { return Kind == BrList; }
117   bool isCatchList() const { return Kind == CatchList; }
118 
119   MCRegister getReg() const override {
120     llvm_unreachable("Assembly inspects a register operand");
121     return 0;
122   }
123 
124   StringRef getToken() const {
125     assert(isToken());
126     return Tok.Tok;
127   }
128 
129   SMLoc getStartLoc() const override { return StartLoc; }
130   SMLoc getEndLoc() const override { return EndLoc; }
131 
132   void addRegOperands(MCInst &, unsigned) const {
133     // Required by the assembly matcher.
134     llvm_unreachable("Assembly matcher creates register operands");
135   }
136 
137   void addImmOperands(MCInst &Inst, unsigned N) const {
138     assert(N == 1 && "Invalid number of operands!");
139     if (Kind == Integer)
140       Inst.addOperand(MCOperand::createImm(Int.Val));
141     else if (Kind == Symbol)
142       Inst.addOperand(MCOperand::createExpr(Sym.Exp));
143     else
144       llvm_unreachable("Should be integer immediate or symbol!");
145   }
146 
147   void addFPImmf32Operands(MCInst &Inst, unsigned N) const {
148     assert(N == 1 && "Invalid number of operands!");
149     if (Kind == Float)
150       Inst.addOperand(
151           MCOperand::createSFPImm(bit_cast<uint32_t>(float(Flt.Val))));
152     else
153       llvm_unreachable("Should be float immediate!");
154   }
155 
156   void addFPImmf64Operands(MCInst &Inst, unsigned N) const {
157     assert(N == 1 && "Invalid number of operands!");
158     if (Kind == Float)
159       Inst.addOperand(MCOperand::createDFPImm(bit_cast<uint64_t>(Flt.Val)));
160     else
161       llvm_unreachable("Should be float immediate!");
162   }
163 
164   void addBrListOperands(MCInst &Inst, unsigned N) const {
165     assert(N == 1 && isBrList() && "Invalid BrList!");
166     for (auto Br : BrL.List)
167       Inst.addOperand(MCOperand::createImm(Br));
168   }
169 
170   void addCatchListOperands(MCInst &Inst, unsigned N) const {
171     assert(N == 1 && isCatchList() && "Invalid CatchList!");
172     Inst.addOperand(MCOperand::createImm(CaL.List.size()));
173     for (auto Ca : CaL.List) {
174       Inst.addOperand(MCOperand::createImm(Ca.Opcode));
175       if (Ca.Opcode == wasm::WASM_OPCODE_CATCH ||
176           Ca.Opcode == wasm::WASM_OPCODE_CATCH_REF)
177         Inst.addOperand(MCOperand::createExpr(Ca.Tag));
178       Inst.addOperand(MCOperand::createImm(Ca.Dest));
179     }
180   }
181 
182   void print(raw_ostream &OS) const override {
183     switch (Kind) {
184     case Token:
185       OS << "Tok:" << Tok.Tok;
186       break;
187     case Integer:
188       OS << "Int:" << Int.Val;
189       break;
190     case Float:
191       OS << "Flt:" << Flt.Val;
192       break;
193     case Symbol:
194       OS << "Sym:" << Sym.Exp;
195       break;
196     case BrList:
197       OS << "BrList:" << BrL.List.size();
198       break;
199     case CatchList:
200       OS << "CaList:" << CaL.List.size();
201       break;
202     }
203   }
204 };
205 
206 // Perhaps this should go somewhere common.
207 static wasm::WasmLimits DefaultLimits() {
208   return {wasm::WASM_LIMITS_FLAG_NONE, 0, 0};
209 }
210 
211 static MCSymbolWasm *GetOrCreateFunctionTableSymbol(MCContext &Ctx,
212                                                     const StringRef &Name,
213                                                     bool is64) {
214   MCSymbolWasm *Sym = cast_or_null<MCSymbolWasm>(Ctx.lookupSymbol(Name));
215   if (Sym) {
216     if (!Sym->isFunctionTable())
217       Ctx.reportError(SMLoc(), "symbol is not a wasm funcref table");
218   } else {
219     Sym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(Name));
220     Sym->setFunctionTable(is64);
221     // The default function table is synthesized by the linker.
222     Sym->setUndefined();
223   }
224   return Sym;
225 }
226 
227 class WebAssemblyAsmParser final : public MCTargetAsmParser {
228   MCAsmParser &Parser;
229   MCAsmLexer &Lexer;
230 
231   // Order of labels, directives and instructions in a .s file have no
232   // syntactical enforcement. This class is a callback from the actual parser,
233   // and yet we have to be feeding data to the streamer in a very particular
234   // order to ensure a correct binary encoding that matches the regular backend
235   // (the streamer does not enforce this). This "state machine" enum helps
236   // guarantee that correct order.
237   enum ParserState {
238     FileStart,
239     FunctionLabel,
240     FunctionStart,
241     FunctionLocals,
242     Instructions,
243     EndFunction,
244     DataSection,
245   } CurrentState = FileStart;
246 
247   // For ensuring blocks are properly nested.
248   enum NestingType {
249     Function,
250     Block,
251     Loop,
252     Try,
253     CatchAll,
254     TryTable,
255     If,
256     Else,
257     Undefined,
258   };
259   struct Nested {
260     NestingType NT;
261     wasm::WasmSignature Sig;
262   };
263   std::vector<Nested> NestingStack;
264 
265   MCSymbolWasm *DefaultFunctionTable = nullptr;
266   MCSymbol *LastFunctionLabel = nullptr;
267 
268   bool is64;
269 
270   WebAssemblyAsmTypeCheck TC;
271   // Don't type check if -no-type-check was set.
272   bool SkipTypeCheck;
273 
274 public:
275   WebAssemblyAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
276                        const MCInstrInfo &MII, const MCTargetOptions &Options)
277       : MCTargetAsmParser(Options, STI, MII), Parser(Parser),
278         Lexer(Parser.getLexer()), is64(STI.getTargetTriple().isArch64Bit()),
279         TC(Parser, MII, is64), SkipTypeCheck(Options.MCNoTypeCheck) {
280     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
281     // Don't type check if this is inline asm, since that is a naked sequence of
282     // instructions without a function/locals decl.
283     auto &SM = Parser.getSourceManager();
284     auto BufferName =
285         SM.getBufferInfo(SM.getMainFileID()).Buffer->getBufferIdentifier();
286     if (BufferName == "<inline asm>")
287       SkipTypeCheck = true;
288   }
289 
290   void Initialize(MCAsmParser &Parser) override {
291     MCAsmParserExtension::Initialize(Parser);
292 
293     DefaultFunctionTable = GetOrCreateFunctionTableSymbol(
294         getContext(), "__indirect_function_table", is64);
295     if (!STI->checkFeatures("+reference-types"))
296       DefaultFunctionTable->setOmitFromLinkingSection();
297   }
298 
299 #define GET_ASSEMBLER_HEADER
300 #include "WebAssemblyGenAsmMatcher.inc"
301 
302   // TODO: This is required to be implemented, but appears unused.
303   bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc) override {
304     llvm_unreachable("parseRegister is not implemented.");
305   }
306   ParseStatus tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
307                                SMLoc &EndLoc) override {
308     llvm_unreachable("tryParseRegister is not implemented.");
309   }
310 
311   bool error(const Twine &Msg, const AsmToken &Tok) {
312     return Parser.Error(Tok.getLoc(), Msg + Tok.getString());
313   }
314 
315   bool error(const Twine &Msg, SMLoc Loc = SMLoc()) {
316     return Parser.Error(Loc.isValid() ? Loc : Lexer.getTok().getLoc(), Msg);
317   }
318 
319   std::pair<StringRef, StringRef> nestingString(NestingType NT) {
320     switch (NT) {
321     case Function:
322       return {"function", "end_function"};
323     case Block:
324       return {"block", "end_block"};
325     case Loop:
326       return {"loop", "end_loop"};
327     case Try:
328       return {"try", "end_try/delegate"};
329     case CatchAll:
330       return {"catch_all", "end_try"};
331     case TryTable:
332       return {"try_table", "end_try_table"};
333     case If:
334       return {"if", "end_if"};
335     case Else:
336       return {"else", "end_if"};
337     default:
338       llvm_unreachable("unknown NestingType");
339     }
340   }
341 
342   void push(NestingType NT, wasm::WasmSignature Sig = wasm::WasmSignature()) {
343     NestingStack.push_back({NT, Sig});
344   }
345 
346   bool pop(StringRef Ins, NestingType NT1, NestingType NT2 = Undefined) {
347     if (NestingStack.empty())
348       return error(Twine("End of block construct with no start: ") + Ins);
349     auto Top = NestingStack.back();
350     if (Top.NT != NT1 && Top.NT != NT2)
351       return error(Twine("Block construct type mismatch, expected: ") +
352                    nestingString(Top.NT).second + ", instead got: " + Ins);
353     TC.setLastSig(Top.Sig);
354     NestingStack.pop_back();
355     return false;
356   }
357 
358   // Pop a NestingType and push a new NestingType with the same signature. Used
359   // for if-else and try-catch(_all).
360   bool popAndPushWithSameSignature(StringRef Ins, NestingType PopNT,
361                                    NestingType PushNT) {
362     if (NestingStack.empty())
363       return error(Twine("End of block construct with no start: ") + Ins);
364     auto Sig = NestingStack.back().Sig;
365     if (pop(Ins, PopNT))
366       return true;
367     push(PushNT, Sig);
368     return false;
369   }
370 
371   bool ensureEmptyNestingStack(SMLoc Loc = SMLoc()) {
372     auto Err = !NestingStack.empty();
373     while (!NestingStack.empty()) {
374       error(Twine("Unmatched block construct(s) at function end: ") +
375                 nestingString(NestingStack.back().NT).first,
376             Loc);
377       NestingStack.pop_back();
378     }
379     return Err;
380   }
381 
382   bool isNext(AsmToken::TokenKind Kind) {
383     auto Ok = Lexer.is(Kind);
384     if (Ok)
385       Parser.Lex();
386     return Ok;
387   }
388 
389   bool expect(AsmToken::TokenKind Kind, const char *KindName) {
390     if (!isNext(Kind))
391       return error(std::string("Expected ") + KindName + ", instead got: ",
392                    Lexer.getTok());
393     return false;
394   }
395 
396   StringRef expectIdent() {
397     if (!Lexer.is(AsmToken::Identifier)) {
398       error("Expected identifier, got: ", Lexer.getTok());
399       return StringRef();
400     }
401     auto Name = Lexer.getTok().getString();
402     Parser.Lex();
403     return Name;
404   }
405 
406   bool parseRegTypeList(SmallVectorImpl<wasm::ValType> &Types) {
407     while (Lexer.is(AsmToken::Identifier)) {
408       auto Type = WebAssembly::parseType(Lexer.getTok().getString());
409       if (!Type)
410         return error("unknown type: ", Lexer.getTok());
411       Types.push_back(*Type);
412       Parser.Lex();
413       if (!isNext(AsmToken::Comma))
414         break;
415     }
416     return false;
417   }
418 
419   void parseSingleInteger(bool IsNegative, OperandVector &Operands) {
420     auto &Int = Lexer.getTok();
421     int64_t Val = Int.getIntVal();
422     if (IsNegative)
423       Val = -Val;
424     Operands.push_back(std::make_unique<WebAssemblyOperand>(
425         Int.getLoc(), Int.getEndLoc(), WebAssemblyOperand::IntOp{Val}));
426     Parser.Lex();
427   }
428 
429   bool parseSingleFloat(bool IsNegative, OperandVector &Operands) {
430     auto &Flt = Lexer.getTok();
431     double Val;
432     if (Flt.getString().getAsDouble(Val, false))
433       return error("Cannot parse real: ", Flt);
434     if (IsNegative)
435       Val = -Val;
436     Operands.push_back(std::make_unique<WebAssemblyOperand>(
437         Flt.getLoc(), Flt.getEndLoc(), WebAssemblyOperand::FltOp{Val}));
438     Parser.Lex();
439     return false;
440   }
441 
442   bool parseSpecialFloatMaybe(bool IsNegative, OperandVector &Operands) {
443     if (Lexer.isNot(AsmToken::Identifier))
444       return true;
445     auto &Flt = Lexer.getTok();
446     auto S = Flt.getString();
447     double Val;
448     if (S.compare_insensitive("infinity") == 0) {
449       Val = std::numeric_limits<double>::infinity();
450     } else if (S.compare_insensitive("nan") == 0) {
451       Val = std::numeric_limits<double>::quiet_NaN();
452     } else {
453       return true;
454     }
455     if (IsNegative)
456       Val = -Val;
457     Operands.push_back(std::make_unique<WebAssemblyOperand>(
458         Flt.getLoc(), Flt.getEndLoc(), WebAssemblyOperand::FltOp{Val}));
459     Parser.Lex();
460     return false;
461   }
462 
463   bool checkForP2AlignIfLoadStore(OperandVector &Operands, StringRef InstName) {
464     // FIXME: there is probably a cleaner way to do this.
465     auto IsLoadStore = InstName.contains(".load") ||
466                        InstName.contains(".store") ||
467                        InstName.contains("prefetch");
468     auto IsAtomic = InstName.contains("atomic.");
469     if (IsLoadStore || IsAtomic) {
470       // Parse load/store operands of the form: offset:p2align=align
471       if (IsLoadStore && isNext(AsmToken::Colon)) {
472         auto Id = expectIdent();
473         if (Id != "p2align")
474           return error("Expected p2align, instead got: " + Id);
475         if (expect(AsmToken::Equal, "="))
476           return true;
477         if (!Lexer.is(AsmToken::Integer))
478           return error("Expected integer constant");
479         parseSingleInteger(false, Operands);
480       } else {
481         // v128.{load,store}{8,16,32,64}_lane has both a memarg and a lane
482         // index. We need to avoid parsing an extra alignment operand for the
483         // lane index.
484         auto IsLoadStoreLane = InstName.contains("_lane");
485         if (IsLoadStoreLane && Operands.size() == 4)
486           return false;
487         // Alignment not specified (or atomics, must use default alignment).
488         // We can't just call WebAssembly::GetDefaultP2Align since we don't have
489         // an opcode until after the assembly matcher, so set a default to fix
490         // up later.
491         auto Tok = Lexer.getTok();
492         Operands.push_back(std::make_unique<WebAssemblyOperand>(
493             Tok.getLoc(), Tok.getEndLoc(), WebAssemblyOperand::IntOp{-1}));
494       }
495     }
496     return false;
497   }
498 
499   void addBlockTypeOperand(OperandVector &Operands, SMLoc NameLoc,
500                            WebAssembly::BlockType BT) {
501     if (BT != WebAssembly::BlockType::Void) {
502       wasm::WasmSignature Sig({static_cast<wasm::ValType>(BT)}, {});
503       TC.setLastSig(Sig);
504       NestingStack.back().Sig = Sig;
505     }
506     Operands.push_back(std::make_unique<WebAssemblyOperand>(
507         NameLoc, NameLoc, WebAssemblyOperand::IntOp{static_cast<int64_t>(BT)}));
508   }
509 
510   bool parseLimits(wasm::WasmLimits *Limits) {
511     auto Tok = Lexer.getTok();
512     if (!Tok.is(AsmToken::Integer))
513       return error("Expected integer constant, instead got: ", Tok);
514     int64_t Val = Tok.getIntVal();
515     assert(Val >= 0);
516     Limits->Minimum = Val;
517     Parser.Lex();
518 
519     if (isNext(AsmToken::Comma)) {
520       Limits->Flags |= wasm::WASM_LIMITS_FLAG_HAS_MAX;
521       auto Tok = Lexer.getTok();
522       if (!Tok.is(AsmToken::Integer))
523         return error("Expected integer constant, instead got: ", Tok);
524       int64_t Val = Tok.getIntVal();
525       assert(Val >= 0);
526       Limits->Maximum = Val;
527       Parser.Lex();
528     }
529     return false;
530   }
531 
532   bool parseFunctionTableOperand(std::unique_ptr<WebAssemblyOperand> *Op) {
533     if (STI->checkFeatures("+reference-types")) {
534       // If the reference-types feature is enabled, there is an explicit table
535       // operand.  To allow the same assembly to be compiled with or without
536       // reference types, we allow the operand to be omitted, in which case we
537       // default to __indirect_function_table.
538       auto &Tok = Lexer.getTok();
539       if (Tok.is(AsmToken::Identifier)) {
540         auto *Sym =
541             GetOrCreateFunctionTableSymbol(getContext(), Tok.getString(), is64);
542         const auto *Val = MCSymbolRefExpr::create(Sym, getContext());
543         *Op = std::make_unique<WebAssemblyOperand>(
544             Tok.getLoc(), Tok.getEndLoc(), WebAssemblyOperand::SymOp{Val});
545         Parser.Lex();
546         return expect(AsmToken::Comma, ",");
547       } else {
548         const auto *Val =
549             MCSymbolRefExpr::create(DefaultFunctionTable, getContext());
550         *Op = std::make_unique<WebAssemblyOperand>(
551             SMLoc(), SMLoc(), WebAssemblyOperand::SymOp{Val});
552         return false;
553       }
554     } else {
555       // For the MVP there is at most one table whose number is 0, but we can't
556       // write a table symbol or issue relocations.  Instead we just ensure the
557       // table is live and write a zero.
558       getStreamer().emitSymbolAttribute(DefaultFunctionTable, MCSA_NoDeadStrip);
559       *Op = std::make_unique<WebAssemblyOperand>(SMLoc(), SMLoc(),
560                                                  WebAssemblyOperand::IntOp{0});
561       return false;
562     }
563   }
564 
565   bool ParseInstruction(ParseInstructionInfo & /*Info*/, StringRef Name,
566                         SMLoc NameLoc, OperandVector &Operands) override {
567     // Note: Name does NOT point into the sourcecode, but to a local, so
568     // use NameLoc instead.
569     Name = StringRef(NameLoc.getPointer(), Name.size());
570 
571     // WebAssembly has instructions with / in them, which AsmLexer parses
572     // as separate tokens, so if we find such tokens immediately adjacent (no
573     // whitespace), expand the name to include them:
574     for (;;) {
575       auto &Sep = Lexer.getTok();
576       if (Sep.getLoc().getPointer() != Name.end() ||
577           Sep.getKind() != AsmToken::Slash)
578         break;
579       // Extend name with /
580       Name = StringRef(Name.begin(), Name.size() + Sep.getString().size());
581       Parser.Lex();
582       // We must now find another identifier, or error.
583       auto &Id = Lexer.getTok();
584       if (Id.getKind() != AsmToken::Identifier ||
585           Id.getLoc().getPointer() != Name.end())
586         return error("Incomplete instruction name: ", Id);
587       Name = StringRef(Name.begin(), Name.size() + Id.getString().size());
588       Parser.Lex();
589     }
590 
591     // Now construct the name as first operand.
592     Operands.push_back(std::make_unique<WebAssemblyOperand>(
593         NameLoc, SMLoc::getFromPointer(Name.end()),
594         WebAssemblyOperand::TokOp{Name}));
595 
596     // If this instruction is part of a control flow structure, ensure
597     // proper nesting.
598     bool ExpectBlockType = false;
599     bool ExpectFuncType = false;
600     bool ExpectCatchList = false;
601     std::unique_ptr<WebAssemblyOperand> FunctionTable;
602     if (Name == "block") {
603       push(Block);
604       ExpectBlockType = true;
605     } else if (Name == "loop") {
606       push(Loop);
607       ExpectBlockType = true;
608     } else if (Name == "try") {
609       push(Try);
610       ExpectBlockType = true;
611     } else if (Name == "if") {
612       push(If);
613       ExpectBlockType = true;
614     } else if (Name == "else") {
615       if (popAndPushWithSameSignature(Name, If, Else))
616         return true;
617     } else if (Name == "catch") {
618       if (popAndPushWithSameSignature(Name, Try, Try))
619         return true;
620     } else if (Name == "catch_all") {
621       if (popAndPushWithSameSignature(Name, Try, CatchAll))
622         return true;
623     } else if (Name == "try_table") {
624       push(TryTable);
625       ExpectBlockType = true;
626       ExpectCatchList = true;
627     } else if (Name == "end_if") {
628       if (pop(Name, If, Else))
629         return true;
630     } else if (Name == "end_try") {
631       if (pop(Name, Try, CatchAll))
632         return true;
633     } else if (Name == "end_try_table") {
634       if (pop(Name, TryTable))
635         return true;
636     } else if (Name == "delegate") {
637       if (pop(Name, Try))
638         return true;
639     } else if (Name == "end_loop") {
640       if (pop(Name, Loop))
641         return true;
642     } else if (Name == "end_block") {
643       if (pop(Name, Block))
644         return true;
645     } else if (Name == "end_function") {
646       ensureLocals(getStreamer());
647       CurrentState = EndFunction;
648       if (pop(Name, Function) || ensureEmptyNestingStack())
649         return true;
650     } else if (Name == "call_indirect" || Name == "return_call_indirect") {
651       // These instructions have differing operand orders in the text format vs
652       // the binary formats.  The MC instructions follow the binary format, so
653       // here we stash away the operand and append it later.
654       if (parseFunctionTableOperand(&FunctionTable))
655         return true;
656       ExpectFuncType = true;
657     }
658 
659     // Returns true if the next tokens are a catch clause
660     auto PeekCatchList = [&]() {
661       if (Lexer.isNot(AsmToken::LParen))
662         return false;
663       AsmToken NextTok = Lexer.peekTok();
664       return NextTok.getKind() == AsmToken::Identifier &&
665              NextTok.getIdentifier().starts_with("catch");
666     };
667 
668     // Parse a multivalue block type
669     if (ExpectFuncType ||
670         (Lexer.is(AsmToken::LParen) && ExpectBlockType && !PeekCatchList())) {
671       // This has a special TYPEINDEX operand which in text we
672       // represent as a signature, such that we can re-build this signature,
673       // attach it to an anonymous symbol, which is what WasmObjectWriter
674       // expects to be able to recreate the actual unique-ified type indices.
675       auto &Ctx = getContext();
676       auto Loc = Parser.getTok();
677       auto Signature = Ctx.createWasmSignature();
678       if (parseSignature(Signature))
679         return true;
680       // Got signature as block type, don't need more
681       TC.setLastSig(*Signature);
682       if (ExpectBlockType)
683         NestingStack.back().Sig = *Signature;
684       ExpectBlockType = false;
685       // The "true" here will cause this to be a nameless symbol.
686       MCSymbol *Sym = Ctx.createTempSymbol("typeindex", true);
687       auto *WasmSym = cast<MCSymbolWasm>(Sym);
688       WasmSym->setSignature(Signature);
689       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
690       const MCExpr *Expr = MCSymbolRefExpr::create(
691           WasmSym, MCSymbolRefExpr::VK_WASM_TYPEINDEX, Ctx);
692       Operands.push_back(std::make_unique<WebAssemblyOperand>(
693           Loc.getLoc(), Loc.getEndLoc(), WebAssemblyOperand::SymOp{Expr}));
694     }
695 
696     // If we are expecting a catch clause list, try to parse it here.
697     //
698     // If there is a multivalue block return type before this catch list, it
699     // should have been parsed above. If there is no return type before
700     // encountering this catch list, this means the type is void.
701     // The case when there is a single block return value and then a catch list
702     // will be handled below in the 'while' loop.
703     if (ExpectCatchList && PeekCatchList()) {
704       if (ExpectBlockType) {
705         ExpectBlockType = false;
706         addBlockTypeOperand(Operands, NameLoc, WebAssembly::BlockType::Void);
707       }
708       if (parseCatchList(Operands))
709         return true;
710       ExpectCatchList = false;
711     }
712 
713     while (Lexer.isNot(AsmToken::EndOfStatement)) {
714       auto &Tok = Lexer.getTok();
715       switch (Tok.getKind()) {
716       case AsmToken::Identifier: {
717         if (!parseSpecialFloatMaybe(false, Operands))
718           break;
719         auto &Id = Lexer.getTok();
720         if (ExpectBlockType) {
721           // Assume this identifier is a block_type.
722           auto BT = WebAssembly::parseBlockType(Id.getString());
723           if (BT == WebAssembly::BlockType::Invalid)
724             return error("Unknown block type: ", Id);
725           addBlockTypeOperand(Operands, NameLoc, BT);
726           ExpectBlockType = false;
727           Parser.Lex();
728           // Now that we've parsed a single block return type, if we are
729           // expecting a catch clause list, try to parse it.
730           if (ExpectCatchList && PeekCatchList()) {
731             if (parseCatchList(Operands))
732               return true;
733             ExpectCatchList = false;
734           }
735         } else {
736           // Assume this identifier is a label.
737           const MCExpr *Val;
738           SMLoc Start = Id.getLoc();
739           SMLoc End;
740           if (Parser.parseExpression(Val, End))
741             return error("Cannot parse symbol: ", Lexer.getTok());
742           Operands.push_back(std::make_unique<WebAssemblyOperand>(
743               Start, End, WebAssemblyOperand::SymOp{Val}));
744           if (checkForP2AlignIfLoadStore(Operands, Name))
745             return true;
746         }
747         break;
748       }
749       case AsmToken::Minus:
750         Parser.Lex();
751         if (Lexer.is(AsmToken::Integer)) {
752           parseSingleInteger(true, Operands);
753           if (checkForP2AlignIfLoadStore(Operands, Name))
754             return true;
755         } else if (Lexer.is(AsmToken::Real)) {
756           if (parseSingleFloat(true, Operands))
757             return true;
758         } else if (!parseSpecialFloatMaybe(true, Operands)) {
759         } else {
760           return error("Expected numeric constant instead got: ",
761                        Lexer.getTok());
762         }
763         break;
764       case AsmToken::Integer:
765         parseSingleInteger(false, Operands);
766         if (checkForP2AlignIfLoadStore(Operands, Name))
767           return true;
768         break;
769       case AsmToken::Real: {
770         if (parseSingleFloat(false, Operands))
771           return true;
772         break;
773       }
774       case AsmToken::LCurly: {
775         Parser.Lex();
776         auto Op = std::make_unique<WebAssemblyOperand>(
777             Tok.getLoc(), Tok.getEndLoc(), WebAssemblyOperand::BrLOp{});
778         if (!Lexer.is(AsmToken::RCurly))
779           for (;;) {
780             Op->BrL.List.push_back(Lexer.getTok().getIntVal());
781             expect(AsmToken::Integer, "integer");
782             if (!isNext(AsmToken::Comma))
783               break;
784           }
785         expect(AsmToken::RCurly, "}");
786         Operands.push_back(std::move(Op));
787         break;
788       }
789       default:
790         return error("Unexpected token in operand: ", Tok);
791       }
792       if (Lexer.isNot(AsmToken::EndOfStatement)) {
793         if (expect(AsmToken::Comma, ","))
794           return true;
795       }
796     }
797 
798     // If we are still expecting to parse a block type or a catch list at this
799     // point, we set them to the default/empty state.
800 
801     // Support blocks with no operands as default to void.
802     if (ExpectBlockType)
803       addBlockTypeOperand(Operands, NameLoc, WebAssembly::BlockType::Void);
804     // If no catch list has been parsed, add an empty catch list operand.
805     if (ExpectCatchList)
806       Operands.push_back(std::make_unique<WebAssemblyOperand>(
807           NameLoc, NameLoc, WebAssemblyOperand::CaLOp{}));
808 
809     if (FunctionTable)
810       Operands.push_back(std::move(FunctionTable));
811     Parser.Lex();
812     return false;
813   }
814 
815   bool parseSignature(wasm::WasmSignature *Signature) {
816     if (expect(AsmToken::LParen, "("))
817       return true;
818     if (parseRegTypeList(Signature->Params))
819       return true;
820     if (expect(AsmToken::RParen, ")"))
821       return true;
822     if (expect(AsmToken::MinusGreater, "->"))
823       return true;
824     if (expect(AsmToken::LParen, "("))
825       return true;
826     if (parseRegTypeList(Signature->Returns))
827       return true;
828     if (expect(AsmToken::RParen, ")"))
829       return true;
830     return false;
831   }
832 
833   bool parseCatchList(OperandVector &Operands) {
834     auto Op = std::make_unique<WebAssemblyOperand>(
835         Lexer.getTok().getLoc(), SMLoc(), WebAssemblyOperand::CaLOp{});
836     SMLoc EndLoc;
837 
838     while (Lexer.is(AsmToken::LParen)) {
839       if (expect(AsmToken::LParen, "("))
840         return true;
841 
842       auto CatchStr = expectIdent();
843       if (CatchStr.empty())
844         return true;
845       uint8_t CatchOpcode =
846           StringSwitch<uint8_t>(CatchStr)
847               .Case("catch", wasm::WASM_OPCODE_CATCH)
848               .Case("catch_ref", wasm::WASM_OPCODE_CATCH_REF)
849               .Case("catch_all", wasm::WASM_OPCODE_CATCH_ALL)
850               .Case("catch_all_ref", wasm::WASM_OPCODE_CATCH_ALL_REF)
851               .Default(0xff);
852       if (CatchOpcode == 0xff)
853         return error(
854             "Expected catch/catch_ref/catch_all/catch_all_ref, instead got: " +
855             CatchStr);
856 
857       const MCExpr *Tag = nullptr;
858       if (CatchOpcode == wasm::WASM_OPCODE_CATCH ||
859           CatchOpcode == wasm::WASM_OPCODE_CATCH_REF) {
860         if (Parser.parseExpression(Tag))
861           return error("Cannot parse symbol: ", Lexer.getTok());
862       }
863 
864       auto &DestTok = Lexer.getTok();
865       if (DestTok.isNot(AsmToken::Integer))
866         return error("Expected integer constant, instead got: ", DestTok);
867       unsigned Dest = DestTok.getIntVal();
868       Parser.Lex();
869 
870       EndLoc = Lexer.getTok().getEndLoc();
871       if (expect(AsmToken::RParen, ")"))
872         return true;
873 
874       Op->CaL.List.push_back({CatchOpcode, Tag, Dest});
875     }
876 
877     Op->EndLoc = EndLoc;
878     Operands.push_back(std::move(Op));
879     return false;
880   }
881 
882   bool CheckDataSection() {
883     if (CurrentState != DataSection) {
884       auto WS = cast<MCSectionWasm>(getStreamer().getCurrentSectionOnly());
885       if (WS && WS->isText())
886         return error("data directive must occur in a data segment: ",
887                      Lexer.getTok());
888     }
889     CurrentState = DataSection;
890     return false;
891   }
892 
893   // This function processes wasm-specific directives streamed to
894   // WebAssemblyTargetStreamer, all others go to the generic parser
895   // (see WasmAsmParser).
896   ParseStatus parseDirective(AsmToken DirectiveID) override {
897     assert(DirectiveID.getKind() == AsmToken::Identifier);
898     auto &Out = getStreamer();
899     auto &TOut =
900         reinterpret_cast<WebAssemblyTargetStreamer &>(*Out.getTargetStreamer());
901     auto &Ctx = Out.getContext();
902 
903     if (DirectiveID.getString() == ".globaltype") {
904       auto SymName = expectIdent();
905       if (SymName.empty())
906         return ParseStatus::Failure;
907       if (expect(AsmToken::Comma, ","))
908         return ParseStatus::Failure;
909       auto TypeTok = Lexer.getTok();
910       auto TypeName = expectIdent();
911       if (TypeName.empty())
912         return ParseStatus::Failure;
913       auto Type = WebAssembly::parseType(TypeName);
914       if (!Type)
915         return error("Unknown type in .globaltype directive: ", TypeTok);
916       // Optional mutable modifier. Default to mutable for historical reasons.
917       // Ideally we would have gone with immutable as the default and used `mut`
918       // as the modifier to match the `.wat` format.
919       bool Mutable = true;
920       if (isNext(AsmToken::Comma)) {
921         TypeTok = Lexer.getTok();
922         auto Id = expectIdent();
923         if (Id.empty())
924           return ParseStatus::Failure;
925         if (Id == "immutable")
926           Mutable = false;
927         else
928           // Should we also allow `mutable` and `mut` here for clarity?
929           return error("Unknown type in .globaltype modifier: ", TypeTok);
930       }
931       // Now set this symbol with the correct type.
932       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
933       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
934       WasmSym->setGlobalType(wasm::WasmGlobalType{uint8_t(*Type), Mutable});
935       // And emit the directive again.
936       TOut.emitGlobalType(WasmSym);
937       return expect(AsmToken::EndOfStatement, "EOL");
938     }
939 
940     if (DirectiveID.getString() == ".tabletype") {
941       // .tabletype SYM, ELEMTYPE[, MINSIZE[, MAXSIZE]]
942       auto SymName = expectIdent();
943       if (SymName.empty())
944         return ParseStatus::Failure;
945       if (expect(AsmToken::Comma, ","))
946         return ParseStatus::Failure;
947 
948       auto ElemTypeTok = Lexer.getTok();
949       auto ElemTypeName = expectIdent();
950       if (ElemTypeName.empty())
951         return ParseStatus::Failure;
952       std::optional<wasm::ValType> ElemType =
953           WebAssembly::parseType(ElemTypeName);
954       if (!ElemType)
955         return error("Unknown type in .tabletype directive: ", ElemTypeTok);
956 
957       wasm::WasmLimits Limits = DefaultLimits();
958       if (isNext(AsmToken::Comma) && parseLimits(&Limits))
959         return ParseStatus::Failure;
960 
961       // Now that we have the name and table type, we can actually create the
962       // symbol
963       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
964       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TABLE);
965       if (is64) {
966         Limits.Flags |= wasm::WASM_LIMITS_FLAG_IS_64;
967       }
968       wasm::WasmTableType Type = {*ElemType, Limits};
969       WasmSym->setTableType(Type);
970       TOut.emitTableType(WasmSym);
971       return expect(AsmToken::EndOfStatement, "EOL");
972     }
973 
974     if (DirectiveID.getString() == ".functype") {
975       // This code has to send things to the streamer similar to
976       // WebAssemblyAsmPrinter::EmitFunctionBodyStart.
977       // TODO: would be good to factor this into a common function, but the
978       // assembler and backend really don't share any common code, and this code
979       // parses the locals separately.
980       auto SymName = expectIdent();
981       if (SymName.empty())
982         return ParseStatus::Failure;
983       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
984       if (WasmSym->isDefined()) {
985         // We push 'Function' either when a label is parsed or a .functype
986         // directive is parsed. The reason it is not easy to do this uniformly
987         // in a single place is,
988         // 1. We can't do this at label parsing time only because there are
989         //    cases we don't have .functype directive before a function label,
990         //    in which case we don't know if the label is a function at the time
991         //    of parsing.
992         // 2. We can't do this at .functype parsing time only because we want to
993         //    detect a function started with a label and not ended correctly
994         //    without encountering a .functype directive after the label.
995         if (CurrentState != FunctionLabel) {
996           // This .functype indicates a start of a function.
997           if (ensureEmptyNestingStack())
998             return ParseStatus::Failure;
999           push(Function);
1000         }
1001         CurrentState = FunctionStart;
1002         LastFunctionLabel = WasmSym;
1003       }
1004       auto Signature = Ctx.createWasmSignature();
1005       if (parseSignature(Signature))
1006         return ParseStatus::Failure;
1007       TC.funcDecl(*Signature);
1008       WasmSym->setSignature(Signature);
1009       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
1010       TOut.emitFunctionType(WasmSym);
1011       // TODO: backend also calls TOut.emitIndIdx, but that is not implemented.
1012       return expect(AsmToken::EndOfStatement, "EOL");
1013     }
1014 
1015     if (DirectiveID.getString() == ".export_name") {
1016       auto SymName = expectIdent();
1017       if (SymName.empty())
1018         return ParseStatus::Failure;
1019       if (expect(AsmToken::Comma, ","))
1020         return ParseStatus::Failure;
1021       auto ExportName = expectIdent();
1022       if (ExportName.empty())
1023         return ParseStatus::Failure;
1024       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
1025       WasmSym->setExportName(Ctx.allocateString(ExportName));
1026       TOut.emitExportName(WasmSym, ExportName);
1027       return expect(AsmToken::EndOfStatement, "EOL");
1028     }
1029 
1030     if (DirectiveID.getString() == ".import_module") {
1031       auto SymName = expectIdent();
1032       if (SymName.empty())
1033         return ParseStatus::Failure;
1034       if (expect(AsmToken::Comma, ","))
1035         return ParseStatus::Failure;
1036       auto ImportModule = expectIdent();
1037       if (ImportModule.empty())
1038         return ParseStatus::Failure;
1039       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
1040       WasmSym->setImportModule(Ctx.allocateString(ImportModule));
1041       TOut.emitImportModule(WasmSym, ImportModule);
1042       return expect(AsmToken::EndOfStatement, "EOL");
1043     }
1044 
1045     if (DirectiveID.getString() == ".import_name") {
1046       auto SymName = expectIdent();
1047       if (SymName.empty())
1048         return ParseStatus::Failure;
1049       if (expect(AsmToken::Comma, ","))
1050         return ParseStatus::Failure;
1051       auto ImportName = expectIdent();
1052       if (ImportName.empty())
1053         return ParseStatus::Failure;
1054       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
1055       WasmSym->setImportName(Ctx.allocateString(ImportName));
1056       TOut.emitImportName(WasmSym, ImportName);
1057       return expect(AsmToken::EndOfStatement, "EOL");
1058     }
1059 
1060     if (DirectiveID.getString() == ".tagtype") {
1061       auto SymName = expectIdent();
1062       if (SymName.empty())
1063         return ParseStatus::Failure;
1064       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
1065       auto Signature = Ctx.createWasmSignature();
1066       if (parseRegTypeList(Signature->Params))
1067         return ParseStatus::Failure;
1068       WasmSym->setSignature(Signature);
1069       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TAG);
1070       TOut.emitTagType(WasmSym);
1071       // TODO: backend also calls TOut.emitIndIdx, but that is not implemented.
1072       return expect(AsmToken::EndOfStatement, "EOL");
1073     }
1074 
1075     if (DirectiveID.getString() == ".local") {
1076       if (CurrentState != FunctionStart)
1077         return error(".local directive should follow the start of a function: ",
1078                      Lexer.getTok());
1079       SmallVector<wasm::ValType, 4> Locals;
1080       if (parseRegTypeList(Locals))
1081         return ParseStatus::Failure;
1082       TC.localDecl(Locals);
1083       TOut.emitLocal(Locals);
1084       CurrentState = FunctionLocals;
1085       return expect(AsmToken::EndOfStatement, "EOL");
1086     }
1087 
1088     if (DirectiveID.getString() == ".int8" ||
1089         DirectiveID.getString() == ".int16" ||
1090         DirectiveID.getString() == ".int32" ||
1091         DirectiveID.getString() == ".int64") {
1092       if (CheckDataSection())
1093         return ParseStatus::Failure;
1094       const MCExpr *Val;
1095       SMLoc End;
1096       if (Parser.parseExpression(Val, End))
1097         return error("Cannot parse .int expression: ", Lexer.getTok());
1098       size_t NumBits = 0;
1099       DirectiveID.getString().drop_front(4).getAsInteger(10, NumBits);
1100       Out.emitValue(Val, NumBits / 8, End);
1101       return expect(AsmToken::EndOfStatement, "EOL");
1102     }
1103 
1104     if (DirectiveID.getString() == ".asciz") {
1105       if (CheckDataSection())
1106         return ParseStatus::Failure;
1107       std::string S;
1108       if (Parser.parseEscapedString(S))
1109         return error("Cannot parse string constant: ", Lexer.getTok());
1110       Out.emitBytes(StringRef(S.c_str(), S.length() + 1));
1111       return expect(AsmToken::EndOfStatement, "EOL");
1112     }
1113 
1114     return ParseStatus::NoMatch; // We didn't process this directive.
1115   }
1116 
1117   // Called either when the first instruction is parsed of the function ends.
1118   void ensureLocals(MCStreamer &Out) {
1119     if (CurrentState == FunctionStart) {
1120       // We haven't seen a .local directive yet. The streamer requires locals to
1121       // be encoded as a prelude to the instructions, so emit an empty list of
1122       // locals here.
1123       auto &TOut = reinterpret_cast<WebAssemblyTargetStreamer &>(
1124           *Out.getTargetStreamer());
1125       TOut.emitLocal(SmallVector<wasm::ValType, 0>());
1126       CurrentState = FunctionLocals;
1127     }
1128   }
1129 
1130   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned & /*Opcode*/,
1131                                OperandVector &Operands, MCStreamer &Out,
1132                                uint64_t &ErrorInfo,
1133                                bool MatchingInlineAsm) override {
1134     MCInst Inst;
1135     Inst.setLoc(IDLoc);
1136     FeatureBitset MissingFeatures;
1137     unsigned MatchResult = MatchInstructionImpl(
1138         Operands, Inst, ErrorInfo, MissingFeatures, MatchingInlineAsm);
1139     switch (MatchResult) {
1140     case Match_Success: {
1141       ensureLocals(Out);
1142       // Fix unknown p2align operands.
1143       auto Align = WebAssembly::GetDefaultP2AlignAny(Inst.getOpcode());
1144       if (Align != -1U) {
1145         auto &Op0 = Inst.getOperand(0);
1146         if (Op0.getImm() == -1)
1147           Op0.setImm(Align);
1148       }
1149       if (is64) {
1150         // Upgrade 32-bit loads/stores to 64-bit. These mostly differ by having
1151         // an offset64 arg instead of offset32, but to the assembler matcher
1152         // they're both immediates so don't get selected for.
1153         auto Opc64 = WebAssembly::getWasm64Opcode(
1154             static_cast<uint16_t>(Inst.getOpcode()));
1155         if (Opc64 >= 0) {
1156           Inst.setOpcode(Opc64);
1157         }
1158       }
1159       if (!SkipTypeCheck && TC.typeCheck(IDLoc, Inst, Operands))
1160         return true;
1161       Out.emitInstruction(Inst, getSTI());
1162       if (CurrentState == EndFunction) {
1163         onEndOfFunction(IDLoc);
1164       } else {
1165         CurrentState = Instructions;
1166       }
1167       return false;
1168     }
1169     case Match_MissingFeature: {
1170       assert(MissingFeatures.count() > 0 && "Expected missing features");
1171       SmallString<128> Message;
1172       raw_svector_ostream OS(Message);
1173       OS << "instruction requires:";
1174       for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)
1175         if (MissingFeatures.test(i))
1176           OS << ' ' << getSubtargetFeatureName(i);
1177       return Parser.Error(IDLoc, Message);
1178     }
1179     case Match_MnemonicFail:
1180       return Parser.Error(IDLoc, "invalid instruction");
1181     case Match_NearMisses:
1182       return Parser.Error(IDLoc, "ambiguous instruction");
1183     case Match_InvalidTiedOperand:
1184     case Match_InvalidOperand: {
1185       SMLoc ErrorLoc = IDLoc;
1186       if (ErrorInfo != ~0ULL) {
1187         if (ErrorInfo >= Operands.size())
1188           return Parser.Error(IDLoc, "too few operands for instruction");
1189         ErrorLoc = Operands[ErrorInfo]->getStartLoc();
1190         if (ErrorLoc == SMLoc())
1191           ErrorLoc = IDLoc;
1192       }
1193       return Parser.Error(ErrorLoc, "invalid operand for instruction");
1194     }
1195     }
1196     llvm_unreachable("Implement any new match types added!");
1197   }
1198 
1199   void doBeforeLabelEmit(MCSymbol *Symbol, SMLoc IDLoc) override {
1200     // Code below only applies to labels in text sections.
1201     auto CWS = cast<MCSectionWasm>(getStreamer().getCurrentSectionOnly());
1202     if (!CWS->isText())
1203       return;
1204 
1205     auto WasmSym = cast<MCSymbolWasm>(Symbol);
1206     // Unlike other targets, we don't allow data in text sections (labels
1207     // declared with .type @object).
1208     if (WasmSym->getType() == wasm::WASM_SYMBOL_TYPE_DATA) {
1209       Parser.Error(IDLoc,
1210                    "Wasm doesn\'t support data symbols in text sections");
1211       return;
1212     }
1213 
1214     // Start a new section for the next function automatically, since our
1215     // object writer expects each function to have its own section. This way
1216     // The user can't forget this "convention".
1217     auto SymName = Symbol->getName();
1218     if (SymName.starts_with(".L"))
1219       return; // Local Symbol.
1220 
1221     // TODO: If the user explicitly creates a new function section, we ignore
1222     // its name when we create this one. It would be nice to honor their
1223     // choice, while still ensuring that we create one if they forget.
1224     // (that requires coordination with WasmAsmParser::parseSectionDirective)
1225     auto SecName = ".text." + SymName;
1226 
1227     auto *Group = CWS->getGroup();
1228     // If the current section is a COMDAT, also set the flag on the symbol.
1229     // TODO: Currently the only place that the symbols' comdat flag matters is
1230     // for importing comdat functions. But there's no way to specify that in
1231     // assembly currently.
1232     if (Group)
1233       WasmSym->setComdat(true);
1234     auto *WS = getContext().getWasmSection(SecName, SectionKind::getText(), 0,
1235                                            Group, MCContext::GenericSectionID);
1236     getStreamer().switchSection(WS);
1237     // Also generate DWARF for this section if requested.
1238     if (getContext().getGenDwarfForAssembly())
1239       getContext().addGenDwarfSection(WS);
1240 
1241     if (WasmSym->isFunction()) {
1242       // We give the location of the label (IDLoc) here, because otherwise the
1243       // lexer's next location will be used, which can be confusing. For
1244       // example:
1245       //
1246       // test0: ; This function does not end properly
1247       //   ...
1248       //
1249       // test1: ; We would like to point to this line for error
1250       //   ...  . Not this line, which can contain any instruction
1251       ensureEmptyNestingStack(IDLoc);
1252       CurrentState = FunctionLabel;
1253       LastFunctionLabel = Symbol;
1254       push(Function);
1255     }
1256   }
1257 
1258   void onEndOfFunction(SMLoc ErrorLoc) {
1259     if (!SkipTypeCheck)
1260       TC.endOfFunction(ErrorLoc);
1261     // Reset the type checker state.
1262     TC.Clear();
1263   }
1264 
1265   void onEndOfFile() override { ensureEmptyNestingStack(); }
1266 };
1267 } // end anonymous namespace
1268 
1269 // Force static initialization.
1270 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyAsmParser() {
1271   RegisterMCAsmParser<WebAssemblyAsmParser> X(getTheWebAssemblyTarget32());
1272   RegisterMCAsmParser<WebAssemblyAsmParser> Y(getTheWebAssemblyTarget64());
1273 }
1274 
1275 #define GET_REGISTER_MATCHER
1276 #define GET_SUBTARGET_FEATURE_NAME
1277 #define GET_MATCHER_IMPLEMENTATION
1278 #include "WebAssemblyGenAsmMatcher.inc"
1279 
1280 StringRef GetMnemonic(unsigned Opc) {
1281   // FIXME: linear search!
1282   for (auto &ME : MatchTable0) {
1283     if (ME.Opcode == Opc) {
1284       return ME.getMnemonic();
1285     }
1286   }
1287   assert(false && "mnemonic not found");
1288   return StringRef();
1289 }
1290