1 //==- WebAssemblyAsmParser.cpp - Assembler for WebAssembly -*- C++ -*-==// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// 9 /// \file 10 /// This file is part of the WebAssembly Assembler. 11 /// 12 /// It contains code to translate a parsed .s file into MCInsts. 13 /// 14 //===----------------------------------------------------------------------===// 15 16 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" 17 #include "MCTargetDesc/WebAssemblyTargetStreamer.h" 18 #include "WebAssembly.h" 19 #include "llvm/MC/MCContext.h" 20 #include "llvm/MC/MCExpr.h" 21 #include "llvm/MC/MCInst.h" 22 #include "llvm/MC/MCInstrInfo.h" 23 #include "llvm/MC/MCParser/MCParsedAsmOperand.h" 24 #include "llvm/MC/MCParser/MCTargetAsmParser.h" 25 #include "llvm/MC/MCSectionWasm.h" 26 #include "llvm/MC/MCStreamer.h" 27 #include "llvm/MC/MCSubtargetInfo.h" 28 #include "llvm/MC/MCSymbol.h" 29 #include "llvm/MC/MCSymbolWasm.h" 30 #include "llvm/Support/Endian.h" 31 #include "llvm/Support/TargetRegistry.h" 32 33 using namespace llvm; 34 35 #define DEBUG_TYPE "wasm-asm-parser" 36 37 namespace { 38 39 /// WebAssemblyOperand - Instances of this class represent the operands in a 40 /// parsed WASM machine instruction. 41 struct WebAssemblyOperand : public MCParsedAsmOperand { 42 enum KindTy { Token, Integer, Float, Symbol, BrList } Kind; 43 44 SMLoc StartLoc, EndLoc; 45 46 struct TokOp { 47 StringRef Tok; 48 }; 49 50 struct IntOp { 51 int64_t Val; 52 }; 53 54 struct FltOp { 55 double Val; 56 }; 57 58 struct SymOp { 59 const MCExpr *Exp; 60 }; 61 62 struct BrLOp { 63 std::vector<unsigned> List; 64 }; 65 66 union { 67 struct TokOp Tok; 68 struct IntOp Int; 69 struct FltOp Flt; 70 struct SymOp Sym; 71 struct BrLOp BrL; 72 }; 73 74 WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, TokOp T) 75 : Kind(K), StartLoc(Start), EndLoc(End), Tok(T) {} 76 WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, IntOp I) 77 : Kind(K), StartLoc(Start), EndLoc(End), Int(I) {} 78 WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, FltOp F) 79 : Kind(K), StartLoc(Start), EndLoc(End), Flt(F) {} 80 WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, SymOp S) 81 : Kind(K), StartLoc(Start), EndLoc(End), Sym(S) {} 82 WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End) 83 : Kind(K), StartLoc(Start), EndLoc(End), BrL() {} 84 85 ~WebAssemblyOperand() { 86 if (isBrList()) 87 BrL.~BrLOp(); 88 } 89 90 bool isToken() const override { return Kind == Token; } 91 bool isImm() const override { 92 return Kind == Integer || Kind == Float || Kind == Symbol; 93 } 94 bool isMem() const override { return false; } 95 bool isReg() const override { return false; } 96 bool isBrList() const { return Kind == BrList; } 97 98 unsigned getReg() const override { 99 llvm_unreachable("Assembly inspects a register operand"); 100 return 0; 101 } 102 103 StringRef getToken() const { 104 assert(isToken()); 105 return Tok.Tok; 106 } 107 108 SMLoc getStartLoc() const override { return StartLoc; } 109 SMLoc getEndLoc() const override { return EndLoc; } 110 111 void addRegOperands(MCInst &, unsigned) const { 112 // Required by the assembly matcher. 113 llvm_unreachable("Assembly matcher creates register operands"); 114 } 115 116 void addImmOperands(MCInst &Inst, unsigned N) const { 117 assert(N == 1 && "Invalid number of operands!"); 118 if (Kind == Integer) 119 Inst.addOperand(MCOperand::createImm(Int.Val)); 120 else if (Kind == Float) 121 Inst.addOperand(MCOperand::createFPImm(Flt.Val)); 122 else if (Kind == Symbol) 123 Inst.addOperand(MCOperand::createExpr(Sym.Exp)); 124 else 125 llvm_unreachable("Should be immediate or symbol!"); 126 } 127 128 void addBrListOperands(MCInst &Inst, unsigned N) const { 129 assert(N == 1 && isBrList() && "Invalid BrList!"); 130 for (auto Br : BrL.List) 131 Inst.addOperand(MCOperand::createImm(Br)); 132 } 133 134 void print(raw_ostream &OS) const override { 135 switch (Kind) { 136 case Token: 137 OS << "Tok:" << Tok.Tok; 138 break; 139 case Integer: 140 OS << "Int:" << Int.Val; 141 break; 142 case Float: 143 OS << "Flt:" << Flt.Val; 144 break; 145 case Symbol: 146 OS << "Sym:" << Sym.Exp; 147 break; 148 case BrList: 149 OS << "BrList:" << BrL.List.size(); 150 break; 151 } 152 } 153 }; 154 155 class WebAssemblyAsmParser final : public MCTargetAsmParser { 156 MCAsmParser &Parser; 157 MCAsmLexer &Lexer; 158 159 // Much like WebAssemblyAsmPrinter in the backend, we have to own these. 160 std::vector<std::unique_ptr<wasm::WasmSignature>> Signatures; 161 162 // Order of labels, directives and instructions in a .s file have no 163 // syntactical enforcement. This class is a callback from the actual parser, 164 // and yet we have to be feeding data to the streamer in a very particular 165 // order to ensure a correct binary encoding that matches the regular backend 166 // (the streamer does not enforce this). This "state machine" enum helps 167 // guarantee that correct order. 168 enum ParserState { 169 FileStart, 170 Label, 171 FunctionStart, 172 FunctionLocals, 173 Instructions, 174 EndFunction, 175 } CurrentState = FileStart; 176 177 // For ensuring blocks are properly nested. 178 enum NestingType { 179 Function, 180 Block, 181 Loop, 182 Try, 183 If, 184 Else, 185 Undefined, 186 }; 187 std::vector<NestingType> NestingStack; 188 189 // We track this to see if a .functype following a label is the same, 190 // as this is how we recognize the start of a function. 191 MCSymbol *LastLabel = nullptr; 192 MCSymbol *LastFunctionLabel = nullptr; 193 194 public: 195 WebAssemblyAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser, 196 const MCInstrInfo &MII, const MCTargetOptions &Options) 197 : MCTargetAsmParser(Options, STI, MII), Parser(Parser), 198 Lexer(Parser.getLexer()) { 199 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits())); 200 } 201 202 #define GET_ASSEMBLER_HEADER 203 #include "WebAssemblyGenAsmMatcher.inc" 204 205 // TODO: This is required to be implemented, but appears unused. 206 bool ParseRegister(unsigned & /*RegNo*/, SMLoc & /*StartLoc*/, 207 SMLoc & /*EndLoc*/) override { 208 llvm_unreachable("ParseRegister is not implemented."); 209 } 210 211 bool error(const Twine &Msg, const AsmToken &Tok) { 212 return Parser.Error(Tok.getLoc(), Msg + Tok.getString()); 213 } 214 215 bool error(const Twine &Msg) { 216 return Parser.Error(Lexer.getTok().getLoc(), Msg); 217 } 218 219 void addSignature(std::unique_ptr<wasm::WasmSignature> &&Sig) { 220 Signatures.push_back(std::move(Sig)); 221 } 222 223 std::pair<StringRef, StringRef> nestingString(NestingType NT) { 224 switch (NT) { 225 case Function: 226 return {"function", "end_function"}; 227 case Block: 228 return {"block", "end_block"}; 229 case Loop: 230 return {"loop", "end_loop"}; 231 case Try: 232 return {"try", "end_try"}; 233 case If: 234 return {"if", "end_if"}; 235 case Else: 236 return {"else", "end_if"}; 237 default: 238 llvm_unreachable("unknown NestingType"); 239 } 240 } 241 242 void push(NestingType NT) { NestingStack.push_back(NT); } 243 244 bool pop(StringRef Ins, NestingType NT1, NestingType NT2 = Undefined) { 245 if (NestingStack.empty()) 246 return error(Twine("End of block construct with no start: ") + Ins); 247 auto Top = NestingStack.back(); 248 if (Top != NT1 && Top != NT2) 249 return error(Twine("Block construct type mismatch, expected: ") + 250 nestingString(Top).second + ", instead got: " + Ins); 251 NestingStack.pop_back(); 252 return false; 253 } 254 255 bool ensureEmptyNestingStack() { 256 auto Err = !NestingStack.empty(); 257 while (!NestingStack.empty()) { 258 error(Twine("Unmatched block construct(s) at function end: ") + 259 nestingString(NestingStack.back()).first); 260 NestingStack.pop_back(); 261 } 262 return Err; 263 } 264 265 bool isNext(AsmToken::TokenKind Kind) { 266 auto Ok = Lexer.is(Kind); 267 if (Ok) 268 Parser.Lex(); 269 return Ok; 270 } 271 272 bool expect(AsmToken::TokenKind Kind, const char *KindName) { 273 if (!isNext(Kind)) 274 return error(std::string("Expected ") + KindName + ", instead got: ", 275 Lexer.getTok()); 276 return false; 277 } 278 279 StringRef expectIdent() { 280 if (!Lexer.is(AsmToken::Identifier)) { 281 error("Expected identifier, got: ", Lexer.getTok()); 282 return StringRef(); 283 } 284 auto Name = Lexer.getTok().getString(); 285 Parser.Lex(); 286 return Name; 287 } 288 289 Optional<wasm::ValType> parseType(const StringRef &Type) { 290 // FIXME: can't use StringSwitch because wasm::ValType doesn't have a 291 // "invalid" value. 292 if (Type == "i32") 293 return wasm::ValType::I32; 294 if (Type == "i64") 295 return wasm::ValType::I64; 296 if (Type == "f32") 297 return wasm::ValType::F32; 298 if (Type == "f64") 299 return wasm::ValType::F64; 300 if (Type == "v128" || Type == "i8x16" || Type == "i16x8" || 301 Type == "i32x4" || Type == "i64x2" || Type == "f32x4" || 302 Type == "f64x2") 303 return wasm::ValType::V128; 304 if (Type == "except_ref") 305 return wasm::ValType::EXCEPT_REF; 306 return Optional<wasm::ValType>(); 307 } 308 309 WebAssembly::ExprType parseBlockType(StringRef ID) { 310 return StringSwitch<WebAssembly::ExprType>(ID) 311 .Case("i32", WebAssembly::ExprType::I32) 312 .Case("i64", WebAssembly::ExprType::I64) 313 .Case("f32", WebAssembly::ExprType::F32) 314 .Case("f64", WebAssembly::ExprType::F64) 315 .Case("v128", WebAssembly::ExprType::V128) 316 .Case("except_ref", WebAssembly::ExprType::ExceptRef) 317 .Case("void", WebAssembly::ExprType::Void) 318 .Default(WebAssembly::ExprType::Invalid); 319 } 320 321 bool parseRegTypeList(SmallVectorImpl<wasm::ValType> &Types) { 322 while (Lexer.is(AsmToken::Identifier)) { 323 auto Type = parseType(Lexer.getTok().getString()); 324 if (!Type) 325 return error("unknown type: ", Lexer.getTok()); 326 Types.push_back(Type.getValue()); 327 Parser.Lex(); 328 if (!isNext(AsmToken::Comma)) 329 break; 330 } 331 return false; 332 } 333 334 void parseSingleInteger(bool IsNegative, OperandVector &Operands) { 335 auto &Int = Lexer.getTok(); 336 int64_t Val = Int.getIntVal(); 337 if (IsNegative) 338 Val = -Val; 339 Operands.push_back(make_unique<WebAssemblyOperand>( 340 WebAssemblyOperand::Integer, Int.getLoc(), Int.getEndLoc(), 341 WebAssemblyOperand::IntOp{Val})); 342 Parser.Lex(); 343 } 344 345 bool parseOperandStartingWithInteger(bool IsNegative, OperandVector &Operands, 346 StringRef InstName) { 347 parseSingleInteger(IsNegative, Operands); 348 // FIXME: there is probably a cleaner way to do this. 349 auto IsLoadStore = InstName.startswith("load") || 350 InstName.startswith("store") || 351 InstName.startswith("atomic"); 352 if (IsLoadStore) { 353 // Parse load/store operands of the form: offset align 354 auto &Offset = Lexer.getTok(); 355 if (Offset.is(AsmToken::Integer)) { 356 parseSingleInteger(false, Operands); 357 } else { 358 // Alignment not specified. 359 // FIXME: correctly derive a default from the instruction. 360 // We can't just call WebAssembly::GetDefaultP2Align since we don't have 361 // an opcode until after the assembly matcher. 362 Operands.push_back(make_unique<WebAssemblyOperand>( 363 WebAssemblyOperand::Integer, Offset.getLoc(), Offset.getEndLoc(), 364 WebAssemblyOperand::IntOp{0})); 365 } 366 } 367 return false; 368 } 369 370 void addBlockTypeOperand(OperandVector &Operands, SMLoc NameLoc, 371 WebAssembly::ExprType BT) { 372 Operands.push_back(make_unique<WebAssemblyOperand>( 373 WebAssemblyOperand::Integer, NameLoc, NameLoc, 374 WebAssemblyOperand::IntOp{static_cast<int64_t>(BT)})); 375 } 376 377 bool ParseInstruction(ParseInstructionInfo & /*Info*/, StringRef Name, 378 SMLoc NameLoc, OperandVector &Operands) override { 379 // Note: Name does NOT point into the sourcecode, but to a local, so 380 // use NameLoc instead. 381 Name = StringRef(NameLoc.getPointer(), Name.size()); 382 383 // WebAssembly has instructions with / in them, which AsmLexer parses 384 // as seperate tokens, so if we find such tokens immediately adjacent (no 385 // whitespace), expand the name to include them: 386 for (;;) { 387 auto &Sep = Lexer.getTok(); 388 if (Sep.getLoc().getPointer() != Name.end() || 389 Sep.getKind() != AsmToken::Slash) 390 break; 391 // Extend name with / 392 Name = StringRef(Name.begin(), Name.size() + Sep.getString().size()); 393 Parser.Lex(); 394 // We must now find another identifier, or error. 395 auto &Id = Lexer.getTok(); 396 if (Id.getKind() != AsmToken::Identifier || 397 Id.getLoc().getPointer() != Name.end()) 398 return error("Incomplete instruction name: ", Id); 399 Name = StringRef(Name.begin(), Name.size() + Id.getString().size()); 400 Parser.Lex(); 401 } 402 403 // Now construct the name as first operand. 404 Operands.push_back(make_unique<WebAssemblyOperand>( 405 WebAssemblyOperand::Token, NameLoc, SMLoc::getFromPointer(Name.end()), 406 WebAssemblyOperand::TokOp{Name})); 407 auto NamePair = Name.split('.'); 408 // If no '.', there is no type prefix. 409 auto BaseName = NamePair.second.empty() ? NamePair.first : NamePair.second; 410 411 // If this instruction is part of a control flow structure, ensure 412 // proper nesting. 413 bool ExpectBlockType = false; 414 if (BaseName == "block") { 415 push(Block); 416 ExpectBlockType = true; 417 } else if (BaseName == "loop") { 418 push(Loop); 419 ExpectBlockType = true; 420 } else if (BaseName == "try") { 421 push(Try); 422 ExpectBlockType = true; 423 } else if (BaseName == "if") { 424 push(If); 425 ExpectBlockType = true; 426 } else if (BaseName == "else") { 427 if (pop(BaseName, If)) 428 return true; 429 push(Else); 430 } else if (BaseName == "catch") { 431 if (pop(BaseName, Try)) 432 return true; 433 push(Try); 434 } else if (BaseName == "catch_all") { 435 if (pop(BaseName, Try)) 436 return true; 437 push(Try); 438 } else if (BaseName == "end_if") { 439 if (pop(BaseName, If, Else)) 440 return true; 441 } else if (BaseName == "end_try") { 442 if (pop(BaseName, Try)) 443 return true; 444 } else if (BaseName == "end_loop") { 445 if (pop(BaseName, Loop)) 446 return true; 447 } else if (BaseName == "end_block") { 448 if (pop(BaseName, Block)) 449 return true; 450 } else if (BaseName == "end_function") { 451 CurrentState = EndFunction; 452 if (pop(BaseName, Function) || ensureEmptyNestingStack()) 453 return true; 454 } 455 456 while (Lexer.isNot(AsmToken::EndOfStatement)) { 457 auto &Tok = Lexer.getTok(); 458 switch (Tok.getKind()) { 459 case AsmToken::Identifier: { 460 auto &Id = Lexer.getTok(); 461 if (ExpectBlockType) { 462 // Assume this identifier is a block_type. 463 auto BT = parseBlockType(Id.getString()); 464 if (BT == WebAssembly::ExprType::Invalid) 465 return error("Unknown block type: ", Id); 466 addBlockTypeOperand(Operands, NameLoc, BT); 467 Parser.Lex(); 468 } else { 469 // Assume this identifier is a label. 470 const MCExpr *Val; 471 SMLoc End; 472 if (Parser.parsePrimaryExpr(Val, End)) 473 return error("Cannot parse symbol: ", Lexer.getTok()); 474 Operands.push_back(make_unique<WebAssemblyOperand>( 475 WebAssemblyOperand::Symbol, Id.getLoc(), Id.getEndLoc(), 476 WebAssemblyOperand::SymOp{Val})); 477 } 478 break; 479 } 480 case AsmToken::Minus: 481 Parser.Lex(); 482 if (Lexer.isNot(AsmToken::Integer)) 483 return error("Expected integer instead got: ", Lexer.getTok()); 484 if (parseOperandStartingWithInteger(true, Operands, BaseName)) 485 return true; 486 break; 487 case AsmToken::Integer: 488 if (parseOperandStartingWithInteger(false, Operands, BaseName)) 489 return true; 490 break; 491 case AsmToken::Real: { 492 double Val; 493 if (Tok.getString().getAsDouble(Val, false)) 494 return error("Cannot parse real: ", Tok); 495 Operands.push_back(make_unique<WebAssemblyOperand>( 496 WebAssemblyOperand::Float, Tok.getLoc(), Tok.getEndLoc(), 497 WebAssemblyOperand::FltOp{Val})); 498 Parser.Lex(); 499 break; 500 } 501 case AsmToken::LCurly: { 502 Parser.Lex(); 503 auto Op = make_unique<WebAssemblyOperand>( 504 WebAssemblyOperand::BrList, Tok.getLoc(), Tok.getEndLoc()); 505 if (!Lexer.is(AsmToken::RCurly)) 506 for (;;) { 507 Op->BrL.List.push_back(Lexer.getTok().getIntVal()); 508 expect(AsmToken::Integer, "integer"); 509 if (!isNext(AsmToken::Comma)) 510 break; 511 } 512 expect(AsmToken::RCurly, "}"); 513 Operands.push_back(std::move(Op)); 514 break; 515 } 516 default: 517 return error("Unexpected token in operand: ", Tok); 518 } 519 if (Lexer.isNot(AsmToken::EndOfStatement)) { 520 if (expect(AsmToken::Comma, ",")) 521 return true; 522 } 523 } 524 if (ExpectBlockType && Operands.size() == 1) { 525 // Support blocks with no operands as default to void. 526 addBlockTypeOperand(Operands, NameLoc, WebAssembly::ExprType::Void); 527 } 528 Parser.Lex(); 529 return false; 530 } 531 532 void onLabelParsed(MCSymbol *Symbol) override { 533 LastLabel = Symbol; 534 CurrentState = Label; 535 } 536 537 bool parseSignature(wasm::WasmSignature *Signature) { 538 if (expect(AsmToken::LParen, "(")) 539 return true; 540 if (parseRegTypeList(Signature->Params)) 541 return true; 542 if (expect(AsmToken::RParen, ")")) 543 return true; 544 if (expect(AsmToken::MinusGreater, "->")) 545 return true; 546 if (expect(AsmToken::LParen, "(")) 547 return true; 548 if (parseRegTypeList(Signature->Returns)) 549 return true; 550 if (expect(AsmToken::RParen, ")")) 551 return true; 552 return false; 553 } 554 555 // This function processes wasm-specific directives streamed to 556 // WebAssemblyTargetStreamer, all others go to the generic parser 557 // (see WasmAsmParser). 558 bool ParseDirective(AsmToken DirectiveID) override { 559 // This function has a really weird return value behavior that is different 560 // from all the other parsing functions: 561 // - return true && no tokens consumed -> don't know this directive / let 562 // the generic parser handle it. 563 // - return true && tokens consumed -> a parsing error occurred. 564 // - return false -> processed this directive successfully. 565 assert(DirectiveID.getKind() == AsmToken::Identifier); 566 auto &Out = getStreamer(); 567 auto &TOut = 568 reinterpret_cast<WebAssemblyTargetStreamer &>(*Out.getTargetStreamer()); 569 auto &Ctx = Out.getContext(); 570 571 // TODO: any time we return an error, at least one token must have been 572 // consumed, otherwise this will not signal an error to the caller. 573 if (DirectiveID.getString() == ".globaltype") { 574 auto SymName = expectIdent(); 575 if (SymName.empty()) 576 return true; 577 if (expect(AsmToken::Comma, ",")) 578 return true; 579 auto TypeTok = Lexer.getTok(); 580 auto TypeName = expectIdent(); 581 if (TypeName.empty()) 582 return true; 583 auto Type = parseType(TypeName); 584 if (!Type) 585 return error("Unknown type in .globaltype directive: ", TypeTok); 586 // Now set this symbol with the correct type. 587 auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName)); 588 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL); 589 WasmSym->setGlobalType( 590 wasm::WasmGlobalType{uint8_t(Type.getValue()), true}); 591 // And emit the directive again. 592 TOut.emitGlobalType(WasmSym); 593 return expect(AsmToken::EndOfStatement, "EOL"); 594 } 595 596 if (DirectiveID.getString() == ".functype") { 597 // This code has to send things to the streamer similar to 598 // WebAssemblyAsmPrinter::EmitFunctionBodyStart. 599 // TODO: would be good to factor this into a common function, but the 600 // assembler and backend really don't share any common code, and this code 601 // parses the locals seperately. 602 auto SymName = expectIdent(); 603 if (SymName.empty()) 604 return true; 605 auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName)); 606 if (CurrentState == Label && WasmSym == LastLabel) { 607 // This .functype indicates a start of a function. 608 if (ensureEmptyNestingStack()) 609 return true; 610 CurrentState = FunctionStart; 611 LastFunctionLabel = LastLabel; 612 push(Function); 613 } 614 auto Signature = make_unique<wasm::WasmSignature>(); 615 if (parseSignature(Signature.get())) 616 return true; 617 WasmSym->setSignature(Signature.get()); 618 addSignature(std::move(Signature)); 619 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION); 620 TOut.emitFunctionType(WasmSym); 621 // TODO: backend also calls TOut.emitIndIdx, but that is not implemented. 622 return expect(AsmToken::EndOfStatement, "EOL"); 623 } 624 625 if (DirectiveID.getString() == ".eventtype") { 626 auto SymName = expectIdent(); 627 if (SymName.empty()) 628 return true; 629 auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName)); 630 auto Signature = make_unique<wasm::WasmSignature>(); 631 if (parseRegTypeList(Signature->Params)) 632 return true; 633 WasmSym->setSignature(Signature.get()); 634 addSignature(std::move(Signature)); 635 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_EVENT); 636 TOut.emitEventType(WasmSym); 637 // TODO: backend also calls TOut.emitIndIdx, but that is not implemented. 638 return expect(AsmToken::EndOfStatement, "EOL"); 639 } 640 641 if (DirectiveID.getString() == ".local") { 642 if (CurrentState != FunctionStart) 643 return error(".local directive should follow the start of a function", 644 Lexer.getTok()); 645 SmallVector<wasm::ValType, 4> Locals; 646 if (parseRegTypeList(Locals)) 647 return true; 648 TOut.emitLocal(Locals); 649 CurrentState = FunctionLocals; 650 return expect(AsmToken::EndOfStatement, "EOL"); 651 } 652 653 return true; // We didn't process this directive. 654 } 655 656 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned & /*Opcode*/, 657 OperandVector &Operands, MCStreamer &Out, 658 uint64_t &ErrorInfo, 659 bool MatchingInlineAsm) override { 660 MCInst Inst; 661 unsigned MatchResult = 662 MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm); 663 switch (MatchResult) { 664 case Match_Success: { 665 if (CurrentState == FunctionStart) { 666 // This is the first instruction in a function, but we haven't seen 667 // a .local directive yet. The streamer requires locals to be encoded 668 // as a prelude to the instructions, so emit an empty list of locals 669 // here. 670 auto &TOut = reinterpret_cast<WebAssemblyTargetStreamer &>( 671 *Out.getTargetStreamer()); 672 TOut.emitLocal(SmallVector<wasm::ValType, 0>()); 673 } 674 Out.EmitInstruction(Inst, getSTI()); 675 if (CurrentState == EndFunction) { 676 onEndOfFunction(); 677 } else { 678 CurrentState = Instructions; 679 } 680 return false; 681 } 682 case Match_MissingFeature: 683 return Parser.Error( 684 IDLoc, "instruction requires a WASM feature not currently enabled"); 685 case Match_MnemonicFail: 686 return Parser.Error(IDLoc, "invalid instruction"); 687 case Match_NearMisses: 688 return Parser.Error(IDLoc, "ambiguous instruction"); 689 case Match_InvalidTiedOperand: 690 case Match_InvalidOperand: { 691 SMLoc ErrorLoc = IDLoc; 692 if (ErrorInfo != ~0ULL) { 693 if (ErrorInfo >= Operands.size()) 694 return Parser.Error(IDLoc, "too few operands for instruction"); 695 ErrorLoc = Operands[ErrorInfo]->getStartLoc(); 696 if (ErrorLoc == SMLoc()) 697 ErrorLoc = IDLoc; 698 } 699 return Parser.Error(ErrorLoc, "invalid operand for instruction"); 700 } 701 } 702 llvm_unreachable("Implement any new match types added!"); 703 } 704 705 void doBeforeLabelEmit(MCSymbol *Symbol) override { 706 // Start a new section for the next function automatically, since our 707 // object writer expects each function to have its own section. This way 708 // The user can't forget this "convention". 709 auto SymName = Symbol->getName(); 710 if (SymName.startswith(".L")) 711 return; // Local Symbol. 712 auto SecName = ".text." + SymName; 713 auto WS = getContext().getWasmSection(SecName, SectionKind::getText()); 714 getStreamer().SwitchSection(WS); 715 } 716 717 void onEndOfFunction() { 718 // Automatically output a .size directive, so it becomes optional for the 719 // user. 720 auto TempSym = getContext().createLinkerPrivateTempSymbol(); 721 getStreamer().EmitLabel(TempSym); 722 auto Start = MCSymbolRefExpr::create(LastLabel, getContext()); 723 auto End = MCSymbolRefExpr::create(TempSym, getContext()); 724 auto Expr = 725 MCBinaryExpr::create(MCBinaryExpr::Sub, End, Start, getContext()); 726 getStreamer().emitELFSize(LastFunctionLabel, Expr); 727 } 728 729 void onEndOfFile() override { ensureEmptyNestingStack(); } 730 }; 731 } // end anonymous namespace 732 733 // Force static initialization. 734 extern "C" void LLVMInitializeWebAssemblyAsmParser() { 735 RegisterMCAsmParser<WebAssemblyAsmParser> X(getTheWebAssemblyTarget32()); 736 RegisterMCAsmParser<WebAssemblyAsmParser> Y(getTheWebAssemblyTarget64()); 737 } 738 739 #define GET_REGISTER_MATCHER 740 #define GET_MATCHER_IMPLEMENTATION 741 #include "WebAssemblyGenAsmMatcher.inc" 742