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 } 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 // For the MVP there is at most one table whose number is 0, but we can't 555 // write a table symbol or issue relocations. Instead we just ensure the 556 // table is live and write a zero. 557 getStreamer().emitSymbolAttribute(DefaultFunctionTable, MCSA_NoDeadStrip); 558 *Op = std::make_unique<WebAssemblyOperand>(SMLoc(), SMLoc(), 559 WebAssemblyOperand::IntOp{0}); 560 return false; 561 } 562 563 bool parseInstruction(ParseInstructionInfo & /*Info*/, StringRef Name, 564 SMLoc NameLoc, OperandVector &Operands) override { 565 // Note: Name does NOT point into the sourcecode, but to a local, so 566 // use NameLoc instead. 567 Name = StringRef(NameLoc.getPointer(), Name.size()); 568 569 // WebAssembly has instructions with / in them, which AsmLexer parses 570 // as separate tokens, so if we find such tokens immediately adjacent (no 571 // whitespace), expand the name to include them: 572 for (;;) { 573 auto &Sep = Lexer.getTok(); 574 if (Sep.getLoc().getPointer() != Name.end() || 575 Sep.getKind() != AsmToken::Slash) 576 break; 577 // Extend name with / 578 Name = StringRef(Name.begin(), Name.size() + Sep.getString().size()); 579 Parser.Lex(); 580 // We must now find another identifier, or error. 581 auto &Id = Lexer.getTok(); 582 if (Id.getKind() != AsmToken::Identifier || 583 Id.getLoc().getPointer() != Name.end()) 584 return error("Incomplete instruction name: ", Id); 585 Name = StringRef(Name.begin(), Name.size() + Id.getString().size()); 586 Parser.Lex(); 587 } 588 589 // Now construct the name as first operand. 590 Operands.push_back(std::make_unique<WebAssemblyOperand>( 591 NameLoc, SMLoc::getFromPointer(Name.end()), 592 WebAssemblyOperand::TokOp{Name})); 593 594 // If this instruction is part of a control flow structure, ensure 595 // proper nesting. 596 bool ExpectBlockType = false; 597 bool ExpectFuncType = false; 598 bool ExpectCatchList = false; 599 std::unique_ptr<WebAssemblyOperand> FunctionTable; 600 if (Name == "block") { 601 push(Block); 602 ExpectBlockType = true; 603 } else if (Name == "loop") { 604 push(Loop); 605 ExpectBlockType = true; 606 } else if (Name == "try") { 607 push(Try); 608 ExpectBlockType = true; 609 } else if (Name == "if") { 610 push(If); 611 ExpectBlockType = true; 612 } else if (Name == "else") { 613 if (popAndPushWithSameSignature(Name, If, Else)) 614 return true; 615 } else if (Name == "catch") { 616 if (popAndPushWithSameSignature(Name, Try, Try)) 617 return true; 618 } else if (Name == "catch_all") { 619 if (popAndPushWithSameSignature(Name, Try, CatchAll)) 620 return true; 621 } else if (Name == "try_table") { 622 push(TryTable); 623 ExpectBlockType = true; 624 ExpectCatchList = true; 625 } else if (Name == "end_if") { 626 if (pop(Name, If, Else)) 627 return true; 628 } else if (Name == "end_try") { 629 if (pop(Name, Try, CatchAll)) 630 return true; 631 } else if (Name == "end_try_table") { 632 if (pop(Name, TryTable)) 633 return true; 634 } else if (Name == "delegate") { 635 if (pop(Name, Try)) 636 return true; 637 } else if (Name == "end_loop") { 638 if (pop(Name, Loop)) 639 return true; 640 } else if (Name == "end_block") { 641 if (pop(Name, Block)) 642 return true; 643 } else if (Name == "end_function") { 644 ensureLocals(getStreamer()); 645 CurrentState = EndFunction; 646 if (pop(Name, Function) || ensureEmptyNestingStack()) 647 return true; 648 } else if (Name == "call_indirect" || Name == "return_call_indirect") { 649 // These instructions have differing operand orders in the text format vs 650 // the binary formats. The MC instructions follow the binary format, so 651 // here we stash away the operand and append it later. 652 if (parseFunctionTableOperand(&FunctionTable)) 653 return true; 654 ExpectFuncType = true; 655 } 656 657 // Returns true if the next tokens are a catch clause 658 auto PeekCatchList = [&]() { 659 if (Lexer.isNot(AsmToken::LParen)) 660 return false; 661 AsmToken NextTok = Lexer.peekTok(); 662 return NextTok.getKind() == AsmToken::Identifier && 663 NextTok.getIdentifier().starts_with("catch"); 664 }; 665 666 // Parse a multivalue block type 667 if (ExpectFuncType || 668 (Lexer.is(AsmToken::LParen) && ExpectBlockType && !PeekCatchList())) { 669 // This has a special TYPEINDEX operand which in text we 670 // represent as a signature, such that we can re-build this signature, 671 // attach it to an anonymous symbol, which is what WasmObjectWriter 672 // expects to be able to recreate the actual unique-ified type indices. 673 auto &Ctx = getContext(); 674 auto Loc = Parser.getTok(); 675 auto *Signature = Ctx.createWasmSignature(); 676 if (parseSignature(Signature)) 677 return true; 678 // Got signature as block type, don't need more 679 TC.setLastSig(*Signature); 680 if (ExpectBlockType) 681 NestingStack.back().Sig = *Signature; 682 ExpectBlockType = false; 683 // The "true" here will cause this to be a nameless symbol. 684 MCSymbol *Sym = Ctx.createTempSymbol("typeindex", true); 685 auto *WasmSym = cast<MCSymbolWasm>(Sym); 686 WasmSym->setSignature(Signature); 687 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION); 688 const MCExpr *Expr = MCSymbolRefExpr::create( 689 WasmSym, MCSymbolRefExpr::VK_WASM_TYPEINDEX, Ctx); 690 Operands.push_back(std::make_unique<WebAssemblyOperand>( 691 Loc.getLoc(), Loc.getEndLoc(), WebAssemblyOperand::SymOp{Expr})); 692 } 693 694 // If we are expecting a catch clause list, try to parse it here. 695 // 696 // If there is a multivalue block return type before this catch list, it 697 // should have been parsed above. If there is no return type before 698 // encountering this catch list, this means the type is void. 699 // The case when there is a single block return value and then a catch list 700 // will be handled below in the 'while' loop. 701 if (ExpectCatchList && PeekCatchList()) { 702 if (ExpectBlockType) { 703 ExpectBlockType = false; 704 addBlockTypeOperand(Operands, NameLoc, WebAssembly::BlockType::Void); 705 } 706 if (parseCatchList(Operands)) 707 return true; 708 ExpectCatchList = false; 709 } 710 711 while (Lexer.isNot(AsmToken::EndOfStatement)) { 712 auto &Tok = Lexer.getTok(); 713 switch (Tok.getKind()) { 714 case AsmToken::Identifier: { 715 if (!parseSpecialFloatMaybe(false, Operands)) 716 break; 717 auto &Id = Lexer.getTok(); 718 if (ExpectBlockType) { 719 // Assume this identifier is a block_type. 720 auto BT = WebAssembly::parseBlockType(Id.getString()); 721 if (BT == WebAssembly::BlockType::Invalid) 722 return error("Unknown block type: ", Id); 723 addBlockTypeOperand(Operands, NameLoc, BT); 724 ExpectBlockType = false; 725 Parser.Lex(); 726 // Now that we've parsed a single block return type, if we are 727 // expecting a catch clause list, try to parse it. 728 if (ExpectCatchList && PeekCatchList()) { 729 if (parseCatchList(Operands)) 730 return true; 731 ExpectCatchList = false; 732 } 733 } else { 734 // Assume this identifier is a label. 735 const MCExpr *Val; 736 SMLoc Start = Id.getLoc(); 737 SMLoc End; 738 if (Parser.parseExpression(Val, End)) 739 return error("Cannot parse symbol: ", Lexer.getTok()); 740 Operands.push_back(std::make_unique<WebAssemblyOperand>( 741 Start, End, WebAssemblyOperand::SymOp{Val})); 742 if (checkForP2AlignIfLoadStore(Operands, Name)) 743 return true; 744 } 745 break; 746 } 747 case AsmToken::Minus: 748 Parser.Lex(); 749 if (Lexer.is(AsmToken::Integer)) { 750 parseSingleInteger(true, Operands); 751 if (checkForP2AlignIfLoadStore(Operands, Name)) 752 return true; 753 } else if (Lexer.is(AsmToken::Real)) { 754 if (parseSingleFloat(true, Operands)) 755 return true; 756 } else if (!parseSpecialFloatMaybe(true, Operands)) { 757 } else { 758 return error("Expected numeric constant instead got: ", 759 Lexer.getTok()); 760 } 761 break; 762 case AsmToken::Integer: 763 parseSingleInteger(false, Operands); 764 if (checkForP2AlignIfLoadStore(Operands, Name)) 765 return true; 766 break; 767 case AsmToken::Real: { 768 if (parseSingleFloat(false, Operands)) 769 return true; 770 break; 771 } 772 case AsmToken::LCurly: { 773 Parser.Lex(); 774 auto Op = std::make_unique<WebAssemblyOperand>( 775 Tok.getLoc(), Tok.getEndLoc(), WebAssemblyOperand::BrLOp{}); 776 if (!Lexer.is(AsmToken::RCurly)) 777 for (;;) { 778 Op->BrL.List.push_back(Lexer.getTok().getIntVal()); 779 expect(AsmToken::Integer, "integer"); 780 if (!isNext(AsmToken::Comma)) 781 break; 782 } 783 expect(AsmToken::RCurly, "}"); 784 Operands.push_back(std::move(Op)); 785 break; 786 } 787 default: 788 return error("Unexpected token in operand: ", Tok); 789 } 790 if (Lexer.isNot(AsmToken::EndOfStatement)) { 791 if (expect(AsmToken::Comma, ",")) 792 return true; 793 } 794 } 795 796 // If we are still expecting to parse a block type or a catch list at this 797 // point, we set them to the default/empty state. 798 799 // Support blocks with no operands as default to void. 800 if (ExpectBlockType) 801 addBlockTypeOperand(Operands, NameLoc, WebAssembly::BlockType::Void); 802 // If no catch list has been parsed, add an empty catch list operand. 803 if (ExpectCatchList) 804 Operands.push_back(std::make_unique<WebAssemblyOperand>( 805 NameLoc, NameLoc, WebAssemblyOperand::CaLOp{})); 806 807 if (FunctionTable) 808 Operands.push_back(std::move(FunctionTable)); 809 Parser.Lex(); 810 return false; 811 } 812 813 bool parseSignature(wasm::WasmSignature *Signature) { 814 if (expect(AsmToken::LParen, "(")) 815 return true; 816 if (parseRegTypeList(Signature->Params)) 817 return true; 818 if (expect(AsmToken::RParen, ")")) 819 return true; 820 if (expect(AsmToken::MinusGreater, "->")) 821 return true; 822 if (expect(AsmToken::LParen, "(")) 823 return true; 824 if (parseRegTypeList(Signature->Returns)) 825 return true; 826 if (expect(AsmToken::RParen, ")")) 827 return true; 828 return false; 829 } 830 831 bool parseCatchList(OperandVector &Operands) { 832 auto Op = std::make_unique<WebAssemblyOperand>( 833 Lexer.getTok().getLoc(), SMLoc(), WebAssemblyOperand::CaLOp{}); 834 SMLoc EndLoc; 835 836 while (Lexer.is(AsmToken::LParen)) { 837 if (expect(AsmToken::LParen, "(")) 838 return true; 839 840 auto CatchStr = expectIdent(); 841 if (CatchStr.empty()) 842 return true; 843 uint8_t CatchOpcode = 844 StringSwitch<uint8_t>(CatchStr) 845 .Case("catch", wasm::WASM_OPCODE_CATCH) 846 .Case("catch_ref", wasm::WASM_OPCODE_CATCH_REF) 847 .Case("catch_all", wasm::WASM_OPCODE_CATCH_ALL) 848 .Case("catch_all_ref", wasm::WASM_OPCODE_CATCH_ALL_REF) 849 .Default(0xff); 850 if (CatchOpcode == 0xff) 851 return error( 852 "Expected catch/catch_ref/catch_all/catch_all_ref, instead got: " + 853 CatchStr); 854 855 const MCExpr *Tag = nullptr; 856 if (CatchOpcode == wasm::WASM_OPCODE_CATCH || 857 CatchOpcode == wasm::WASM_OPCODE_CATCH_REF) { 858 if (Parser.parseExpression(Tag)) 859 return error("Cannot parse symbol: ", Lexer.getTok()); 860 } 861 862 auto &DestTok = Lexer.getTok(); 863 if (DestTok.isNot(AsmToken::Integer)) 864 return error("Expected integer constant, instead got: ", DestTok); 865 unsigned Dest = DestTok.getIntVal(); 866 Parser.Lex(); 867 868 EndLoc = Lexer.getTok().getEndLoc(); 869 if (expect(AsmToken::RParen, ")")) 870 return true; 871 872 Op->CaL.List.push_back({CatchOpcode, Tag, Dest}); 873 } 874 875 Op->EndLoc = EndLoc; 876 Operands.push_back(std::move(Op)); 877 return false; 878 } 879 880 bool checkDataSection() { 881 if (CurrentState != DataSection) { 882 auto *WS = cast<MCSectionWasm>(getStreamer().getCurrentSectionOnly()); 883 if (WS && WS->isText()) 884 return error("data directive must occur in a data segment: ", 885 Lexer.getTok()); 886 } 887 CurrentState = DataSection; 888 return false; 889 } 890 891 // This function processes wasm-specific directives streamed to 892 // WebAssemblyTargetStreamer, all others go to the generic parser 893 // (see WasmAsmParser). 894 ParseStatus parseDirective(AsmToken DirectiveID) override { 895 assert(DirectiveID.getKind() == AsmToken::Identifier); 896 auto &Out = getStreamer(); 897 auto &TOut = 898 reinterpret_cast<WebAssemblyTargetStreamer &>(*Out.getTargetStreamer()); 899 auto &Ctx = Out.getContext(); 900 901 if (DirectiveID.getString() == ".globaltype") { 902 auto SymName = expectIdent(); 903 if (SymName.empty()) 904 return ParseStatus::Failure; 905 if (expect(AsmToken::Comma, ",")) 906 return ParseStatus::Failure; 907 auto TypeTok = Lexer.getTok(); 908 auto TypeName = expectIdent(); 909 if (TypeName.empty()) 910 return ParseStatus::Failure; 911 auto Type = WebAssembly::parseType(TypeName); 912 if (!Type) 913 return error("Unknown type in .globaltype directive: ", TypeTok); 914 // Optional mutable modifier. Default to mutable for historical reasons. 915 // Ideally we would have gone with immutable as the default and used `mut` 916 // as the modifier to match the `.wat` format. 917 bool Mutable = true; 918 if (isNext(AsmToken::Comma)) { 919 TypeTok = Lexer.getTok(); 920 auto Id = expectIdent(); 921 if (Id.empty()) 922 return ParseStatus::Failure; 923 if (Id == "immutable") 924 Mutable = false; 925 else 926 // Should we also allow `mutable` and `mut` here for clarity? 927 return error("Unknown type in .globaltype modifier: ", TypeTok); 928 } 929 // Now set this symbol with the correct type. 930 auto *WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName)); 931 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL); 932 WasmSym->setGlobalType(wasm::WasmGlobalType{uint8_t(*Type), Mutable}); 933 // And emit the directive again. 934 TOut.emitGlobalType(WasmSym); 935 return expect(AsmToken::EndOfStatement, "EOL"); 936 } 937 938 if (DirectiveID.getString() == ".tabletype") { 939 // .tabletype SYM, ELEMTYPE[, MINSIZE[, MAXSIZE]] 940 auto SymName = expectIdent(); 941 if (SymName.empty()) 942 return ParseStatus::Failure; 943 if (expect(AsmToken::Comma, ",")) 944 return ParseStatus::Failure; 945 946 auto ElemTypeTok = Lexer.getTok(); 947 auto ElemTypeName = expectIdent(); 948 if (ElemTypeName.empty()) 949 return ParseStatus::Failure; 950 std::optional<wasm::ValType> ElemType = 951 WebAssembly::parseType(ElemTypeName); 952 if (!ElemType) 953 return error("Unknown type in .tabletype directive: ", ElemTypeTok); 954 955 wasm::WasmLimits Limits = defaultLimits(); 956 if (isNext(AsmToken::Comma) && parseLimits(&Limits)) 957 return ParseStatus::Failure; 958 959 // Now that we have the name and table type, we can actually create the 960 // symbol 961 auto *WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName)); 962 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TABLE); 963 if (Is64) { 964 Limits.Flags |= wasm::WASM_LIMITS_FLAG_IS_64; 965 } 966 wasm::WasmTableType Type = {*ElemType, Limits}; 967 WasmSym->setTableType(Type); 968 TOut.emitTableType(WasmSym); 969 return expect(AsmToken::EndOfStatement, "EOL"); 970 } 971 972 if (DirectiveID.getString() == ".functype") { 973 // This code has to send things to the streamer similar to 974 // WebAssemblyAsmPrinter::EmitFunctionBodyStart. 975 // TODO: would be good to factor this into a common function, but the 976 // assembler and backend really don't share any common code, and this code 977 // parses the locals separately. 978 auto SymName = expectIdent(); 979 if (SymName.empty()) 980 return ParseStatus::Failure; 981 auto *WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName)); 982 if (WasmSym->isDefined()) { 983 // We push 'Function' either when a label is parsed or a .functype 984 // directive is parsed. The reason it is not easy to do this uniformly 985 // in a single place is, 986 // 1. We can't do this at label parsing time only because there are 987 // cases we don't have .functype directive before a function label, 988 // in which case we don't know if the label is a function at the time 989 // of parsing. 990 // 2. We can't do this at .functype parsing time only because we want to 991 // detect a function started with a label and not ended correctly 992 // without encountering a .functype directive after the label. 993 if (CurrentState != FunctionLabel) { 994 // This .functype indicates a start of a function. 995 if (ensureEmptyNestingStack()) 996 return ParseStatus::Failure; 997 push(Function); 998 } 999 CurrentState = FunctionStart; 1000 LastFunctionLabel = WasmSym; 1001 } 1002 auto *Signature = Ctx.createWasmSignature(); 1003 if (parseSignature(Signature)) 1004 return ParseStatus::Failure; 1005 TC.funcDecl(*Signature); 1006 WasmSym->setSignature(Signature); 1007 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION); 1008 TOut.emitFunctionType(WasmSym); 1009 // TODO: backend also calls TOut.emitIndIdx, but that is not implemented. 1010 return expect(AsmToken::EndOfStatement, "EOL"); 1011 } 1012 1013 if (DirectiveID.getString() == ".export_name") { 1014 auto SymName = expectIdent(); 1015 if (SymName.empty()) 1016 return ParseStatus::Failure; 1017 if (expect(AsmToken::Comma, ",")) 1018 return ParseStatus::Failure; 1019 auto ExportName = expectIdent(); 1020 if (ExportName.empty()) 1021 return ParseStatus::Failure; 1022 auto *WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName)); 1023 WasmSym->setExportName(Ctx.allocateString(ExportName)); 1024 TOut.emitExportName(WasmSym, ExportName); 1025 return expect(AsmToken::EndOfStatement, "EOL"); 1026 } 1027 1028 if (DirectiveID.getString() == ".import_module") { 1029 auto SymName = expectIdent(); 1030 if (SymName.empty()) 1031 return ParseStatus::Failure; 1032 if (expect(AsmToken::Comma, ",")) 1033 return ParseStatus::Failure; 1034 auto ImportModule = expectIdent(); 1035 if (ImportModule.empty()) 1036 return ParseStatus::Failure; 1037 auto *WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName)); 1038 WasmSym->setImportModule(Ctx.allocateString(ImportModule)); 1039 TOut.emitImportModule(WasmSym, ImportModule); 1040 return expect(AsmToken::EndOfStatement, "EOL"); 1041 } 1042 1043 if (DirectiveID.getString() == ".import_name") { 1044 auto SymName = expectIdent(); 1045 if (SymName.empty()) 1046 return ParseStatus::Failure; 1047 if (expect(AsmToken::Comma, ",")) 1048 return ParseStatus::Failure; 1049 auto ImportName = expectIdent(); 1050 if (ImportName.empty()) 1051 return ParseStatus::Failure; 1052 auto *WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName)); 1053 WasmSym->setImportName(Ctx.allocateString(ImportName)); 1054 TOut.emitImportName(WasmSym, ImportName); 1055 return expect(AsmToken::EndOfStatement, "EOL"); 1056 } 1057 1058 if (DirectiveID.getString() == ".tagtype") { 1059 auto SymName = expectIdent(); 1060 if (SymName.empty()) 1061 return ParseStatus::Failure; 1062 auto *WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName)); 1063 auto *Signature = Ctx.createWasmSignature(); 1064 if (parseRegTypeList(Signature->Params)) 1065 return ParseStatus::Failure; 1066 WasmSym->setSignature(Signature); 1067 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TAG); 1068 TOut.emitTagType(WasmSym); 1069 // TODO: backend also calls TOut.emitIndIdx, but that is not implemented. 1070 return expect(AsmToken::EndOfStatement, "EOL"); 1071 } 1072 1073 if (DirectiveID.getString() == ".local") { 1074 if (CurrentState != FunctionStart) 1075 return error(".local directive should follow the start of a function: ", 1076 Lexer.getTok()); 1077 SmallVector<wasm::ValType, 4> Locals; 1078 if (parseRegTypeList(Locals)) 1079 return ParseStatus::Failure; 1080 TC.localDecl(Locals); 1081 TOut.emitLocal(Locals); 1082 CurrentState = FunctionLocals; 1083 return expect(AsmToken::EndOfStatement, "EOL"); 1084 } 1085 1086 if (DirectiveID.getString() == ".int8" || 1087 DirectiveID.getString() == ".int16" || 1088 DirectiveID.getString() == ".int32" || 1089 DirectiveID.getString() == ".int64") { 1090 if (checkDataSection()) 1091 return ParseStatus::Failure; 1092 const MCExpr *Val; 1093 SMLoc End; 1094 if (Parser.parseExpression(Val, End)) 1095 return error("Cannot parse .int expression: ", Lexer.getTok()); 1096 size_t NumBits = 0; 1097 DirectiveID.getString().drop_front(4).getAsInteger(10, NumBits); 1098 Out.emitValue(Val, NumBits / 8, End); 1099 return expect(AsmToken::EndOfStatement, "EOL"); 1100 } 1101 1102 if (DirectiveID.getString() == ".asciz") { 1103 if (checkDataSection()) 1104 return ParseStatus::Failure; 1105 std::string S; 1106 if (Parser.parseEscapedString(S)) 1107 return error("Cannot parse string constant: ", Lexer.getTok()); 1108 Out.emitBytes(StringRef(S.c_str(), S.length() + 1)); 1109 return expect(AsmToken::EndOfStatement, "EOL"); 1110 } 1111 1112 return ParseStatus::NoMatch; // We didn't process this directive. 1113 } 1114 1115 // Called either when the first instruction is parsed of the function ends. 1116 void ensureLocals(MCStreamer &Out) { 1117 if (CurrentState == FunctionStart) { 1118 // We haven't seen a .local directive yet. The streamer requires locals to 1119 // be encoded as a prelude to the instructions, so emit an empty list of 1120 // locals here. 1121 auto &TOut = reinterpret_cast<WebAssemblyTargetStreamer &>( 1122 *Out.getTargetStreamer()); 1123 TOut.emitLocal(SmallVector<wasm::ValType, 0>()); 1124 CurrentState = FunctionLocals; 1125 } 1126 } 1127 1128 bool matchAndEmitInstruction(SMLoc IDLoc, unsigned & /*Opcode*/, 1129 OperandVector &Operands, MCStreamer &Out, 1130 uint64_t &ErrorInfo, 1131 bool MatchingInlineAsm) override { 1132 MCInst Inst; 1133 Inst.setLoc(IDLoc); 1134 FeatureBitset MissingFeatures; 1135 unsigned MatchResult = MatchInstructionImpl( 1136 Operands, Inst, ErrorInfo, MissingFeatures, MatchingInlineAsm); 1137 switch (MatchResult) { 1138 case Match_Success: { 1139 ensureLocals(Out); 1140 // Fix unknown p2align operands. 1141 auto Align = WebAssembly::GetDefaultP2AlignAny(Inst.getOpcode()); 1142 if (Align != -1U) { 1143 auto &Op0 = Inst.getOperand(0); 1144 if (Op0.getImm() == -1) 1145 Op0.setImm(Align); 1146 } 1147 if (Is64) { 1148 // Upgrade 32-bit loads/stores to 64-bit. These mostly differ by having 1149 // an offset64 arg instead of offset32, but to the assembler matcher 1150 // they're both immediates so don't get selected for. 1151 auto Opc64 = WebAssembly::getWasm64Opcode( 1152 static_cast<uint16_t>(Inst.getOpcode())); 1153 if (Opc64 >= 0) { 1154 Inst.setOpcode(Opc64); 1155 } 1156 } 1157 if (!SkipTypeCheck && TC.typeCheck(IDLoc, Inst, Operands)) 1158 return true; 1159 Out.emitInstruction(Inst, getSTI()); 1160 if (CurrentState == EndFunction) { 1161 onEndOfFunction(IDLoc); 1162 } else { 1163 CurrentState = Instructions; 1164 } 1165 return false; 1166 } 1167 case Match_MissingFeature: { 1168 assert(MissingFeatures.count() > 0 && "Expected missing features"); 1169 SmallString<128> Message; 1170 raw_svector_ostream OS(Message); 1171 OS << "instruction requires:"; 1172 for (unsigned I = 0, E = MissingFeatures.size(); I != E; ++I) 1173 if (MissingFeatures.test(I)) 1174 OS << ' ' << getSubtargetFeatureName(I); 1175 return Parser.Error(IDLoc, Message); 1176 } 1177 case Match_MnemonicFail: 1178 return Parser.Error(IDLoc, "invalid instruction"); 1179 case Match_NearMisses: 1180 return Parser.Error(IDLoc, "ambiguous instruction"); 1181 case Match_InvalidTiedOperand: 1182 case Match_InvalidOperand: { 1183 SMLoc ErrorLoc = IDLoc; 1184 if (ErrorInfo != ~0ULL) { 1185 if (ErrorInfo >= Operands.size()) 1186 return Parser.Error(IDLoc, "too few operands for instruction"); 1187 ErrorLoc = Operands[ErrorInfo]->getStartLoc(); 1188 if (ErrorLoc == SMLoc()) 1189 ErrorLoc = IDLoc; 1190 } 1191 return Parser.Error(ErrorLoc, "invalid operand for instruction"); 1192 } 1193 } 1194 llvm_unreachable("Implement any new match types added!"); 1195 } 1196 1197 void doBeforeLabelEmit(MCSymbol *Symbol, SMLoc IDLoc) override { 1198 // Code below only applies to labels in text sections. 1199 auto *CWS = cast<MCSectionWasm>(getStreamer().getCurrentSectionOnly()); 1200 if (!CWS->isText()) 1201 return; 1202 1203 auto *WasmSym = cast<MCSymbolWasm>(Symbol); 1204 // Unlike other targets, we don't allow data in text sections (labels 1205 // declared with .type @object). 1206 if (WasmSym->getType() == wasm::WASM_SYMBOL_TYPE_DATA) { 1207 Parser.Error(IDLoc, 1208 "Wasm doesn\'t support data symbols in text sections"); 1209 return; 1210 } 1211 1212 // Start a new section for the next function automatically, since our 1213 // object writer expects each function to have its own section. This way 1214 // The user can't forget this "convention". 1215 auto SymName = Symbol->getName(); 1216 if (SymName.starts_with(".L")) 1217 return; // Local Symbol. 1218 1219 // TODO: If the user explicitly creates a new function section, we ignore 1220 // its name when we create this one. It would be nice to honor their 1221 // choice, while still ensuring that we create one if they forget. 1222 // (that requires coordination with WasmAsmParser::parseSectionDirective) 1223 std::string SecName = (".text." + SymName).str(); 1224 1225 auto *Group = CWS->getGroup(); 1226 // If the current section is a COMDAT, also set the flag on the symbol. 1227 // TODO: Currently the only place that the symbols' comdat flag matters is 1228 // for importing comdat functions. But there's no way to specify that in 1229 // assembly currently. 1230 if (Group) 1231 WasmSym->setComdat(true); 1232 auto *WS = getContext().getWasmSection(SecName, SectionKind::getText(), 0, 1233 Group, MCContext::GenericSectionID); 1234 getStreamer().switchSection(WS); 1235 // Also generate DWARF for this section if requested. 1236 if (getContext().getGenDwarfForAssembly()) 1237 getContext().addGenDwarfSection(WS); 1238 1239 if (WasmSym->isFunction()) { 1240 // We give the location of the label (IDLoc) here, because otherwise the 1241 // lexer's next location will be used, which can be confusing. For 1242 // example: 1243 // 1244 // test0: ; This function does not end properly 1245 // ... 1246 // 1247 // test1: ; We would like to point to this line for error 1248 // ... . Not this line, which can contain any instruction 1249 ensureEmptyNestingStack(IDLoc); 1250 CurrentState = FunctionLabel; 1251 LastFunctionLabel = Symbol; 1252 push(Function); 1253 } 1254 } 1255 1256 void onEndOfFunction(SMLoc ErrorLoc) { 1257 if (!SkipTypeCheck) 1258 TC.endOfFunction(ErrorLoc); 1259 // Reset the type checker state. 1260 TC.clear(); 1261 } 1262 1263 void onEndOfFile() override { ensureEmptyNestingStack(); } 1264 }; 1265 } // end anonymous namespace 1266 1267 // Force static initialization. 1268 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyAsmParser() { 1269 RegisterMCAsmParser<WebAssemblyAsmParser> X(getTheWebAssemblyTarget32()); 1270 RegisterMCAsmParser<WebAssemblyAsmParser> Y(getTheWebAssemblyTarget64()); 1271 } 1272 1273 #define GET_REGISTER_MATCHER 1274 #define GET_SUBTARGET_FEATURE_NAME 1275 #define GET_MATCHER_IMPLEMENTATION 1276 #include "WebAssemblyGenAsmMatcher.inc" 1277 1278 StringRef getMnemonic(unsigned Opc) { 1279 // FIXME: linear search! 1280 for (auto &ME : MatchTable0) { 1281 if (ME.Opcode == Opc) { 1282 return ME.getMnemonic(); 1283 } 1284 } 1285 assert(false && "mnemonic not found"); 1286 return StringRef(); 1287 } 1288