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