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.startswith("load") || 352 InstName.startswith("store"); 353 auto IsAtomic = InstName.startswith("atomic"); 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 auto NamePair = Name.split('.'); 417 // If no '.', there is no type prefix. 418 auto BaseName = NamePair.second.empty() ? NamePair.first : NamePair.second; 419 420 // If this instruction is part of a control flow structure, ensure 421 // proper nesting. 422 bool ExpectBlockType = false; 423 if (BaseName == "block") { 424 push(Block); 425 ExpectBlockType = true; 426 } else if (BaseName == "loop") { 427 push(Loop); 428 ExpectBlockType = true; 429 } else if (BaseName == "try") { 430 push(Try); 431 ExpectBlockType = true; 432 } else if (BaseName == "if") { 433 push(If); 434 ExpectBlockType = true; 435 } else if (BaseName == "else") { 436 if (pop(BaseName, If)) 437 return true; 438 push(Else); 439 } else if (BaseName == "catch") { 440 if (pop(BaseName, Try)) 441 return true; 442 push(Try); 443 } else if (BaseName == "end_if") { 444 if (pop(BaseName, If, Else)) 445 return true; 446 } else if (BaseName == "end_try") { 447 if (pop(BaseName, Try)) 448 return true; 449 } else if (BaseName == "end_loop") { 450 if (pop(BaseName, Loop)) 451 return true; 452 } else if (BaseName == "end_block") { 453 if (pop(BaseName, Block)) 454 return true; 455 } else if (BaseName == "end_function") { 456 CurrentState = EndFunction; 457 if (pop(BaseName, Function) || ensureEmptyNestingStack()) 458 return true; 459 } 460 461 while (Lexer.isNot(AsmToken::EndOfStatement)) { 462 auto &Tok = Lexer.getTok(); 463 switch (Tok.getKind()) { 464 case AsmToken::Identifier: { 465 auto &Id = Lexer.getTok(); 466 if (ExpectBlockType) { 467 // Assume this identifier is a block_type. 468 auto BT = parseBlockType(Id.getString()); 469 if (BT == WebAssembly::ExprType::Invalid) 470 return error("Unknown block type: ", Id); 471 addBlockTypeOperand(Operands, NameLoc, BT); 472 Parser.Lex(); 473 } else { 474 // Assume this identifier is a label. 475 const MCExpr *Val; 476 SMLoc End; 477 if (Parser.parsePrimaryExpr(Val, End)) 478 return error("Cannot parse symbol: ", Lexer.getTok()); 479 Operands.push_back(make_unique<WebAssemblyOperand>( 480 WebAssemblyOperand::Symbol, Id.getLoc(), Id.getEndLoc(), 481 WebAssemblyOperand::SymOp{Val})); 482 } 483 break; 484 } 485 case AsmToken::Minus: 486 Parser.Lex(); 487 if (Lexer.isNot(AsmToken::Integer)) 488 return error("Expected integer instead got: ", Lexer.getTok()); 489 if (parseOperandStartingWithInteger(true, Operands, BaseName)) 490 return true; 491 break; 492 case AsmToken::Integer: 493 if (parseOperandStartingWithInteger(false, Operands, BaseName)) 494 return true; 495 break; 496 case AsmToken::Real: { 497 double Val; 498 if (Tok.getString().getAsDouble(Val, false)) 499 return error("Cannot parse real: ", Tok); 500 Operands.push_back(make_unique<WebAssemblyOperand>( 501 WebAssemblyOperand::Float, Tok.getLoc(), Tok.getEndLoc(), 502 WebAssemblyOperand::FltOp{Val})); 503 Parser.Lex(); 504 break; 505 } 506 case AsmToken::LCurly: { 507 Parser.Lex(); 508 auto Op = make_unique<WebAssemblyOperand>( 509 WebAssemblyOperand::BrList, Tok.getLoc(), Tok.getEndLoc()); 510 if (!Lexer.is(AsmToken::RCurly)) 511 for (;;) { 512 Op->BrL.List.push_back(Lexer.getTok().getIntVal()); 513 expect(AsmToken::Integer, "integer"); 514 if (!isNext(AsmToken::Comma)) 515 break; 516 } 517 expect(AsmToken::RCurly, "}"); 518 Operands.push_back(std::move(Op)); 519 break; 520 } 521 default: 522 return error("Unexpected token in operand: ", Tok); 523 } 524 if (Lexer.isNot(AsmToken::EndOfStatement)) { 525 if (expect(AsmToken::Comma, ",")) 526 return true; 527 } 528 } 529 if (ExpectBlockType && Operands.size() == 1) { 530 // Support blocks with no operands as default to void. 531 addBlockTypeOperand(Operands, NameLoc, WebAssembly::ExprType::Void); 532 } 533 Parser.Lex(); 534 return false; 535 } 536 537 void onLabelParsed(MCSymbol *Symbol) override { 538 LastLabel = Symbol; 539 CurrentState = Label; 540 } 541 542 bool parseSignature(wasm::WasmSignature *Signature) { 543 if (expect(AsmToken::LParen, "(")) 544 return true; 545 if (parseRegTypeList(Signature->Params)) 546 return true; 547 if (expect(AsmToken::RParen, ")")) 548 return true; 549 if (expect(AsmToken::MinusGreater, "->")) 550 return true; 551 if (expect(AsmToken::LParen, "(")) 552 return true; 553 if (parseRegTypeList(Signature->Returns)) 554 return true; 555 if (expect(AsmToken::RParen, ")")) 556 return true; 557 return false; 558 } 559 560 bool CheckDataSection() { 561 if (CurrentState != DataSection) { 562 auto WS = cast<MCSectionWasm>(getStreamer().getCurrentSection().first); 563 if (WS && WS->getKind().isText()) 564 return error("data directive must occur in a data segment: ", 565 Lexer.getTok()); 566 } 567 CurrentState = DataSection; 568 return false; 569 } 570 571 // This function processes wasm-specific directives streamed to 572 // WebAssemblyTargetStreamer, all others go to the generic parser 573 // (see WasmAsmParser). 574 bool ParseDirective(AsmToken DirectiveID) override { 575 // This function has a really weird return value behavior that is different 576 // from all the other parsing functions: 577 // - return true && no tokens consumed -> don't know this directive / let 578 // the generic parser handle it. 579 // - return true && tokens consumed -> a parsing error occurred. 580 // - return false -> processed this directive successfully. 581 assert(DirectiveID.getKind() == AsmToken::Identifier); 582 auto &Out = getStreamer(); 583 auto &TOut = 584 reinterpret_cast<WebAssemblyTargetStreamer &>(*Out.getTargetStreamer()); 585 auto &Ctx = Out.getContext(); 586 587 // TODO: any time we return an error, at least one token must have been 588 // consumed, otherwise this will not signal an error to the caller. 589 if (DirectiveID.getString() == ".globaltype") { 590 auto SymName = expectIdent(); 591 if (SymName.empty()) 592 return true; 593 if (expect(AsmToken::Comma, ",")) 594 return true; 595 auto TypeTok = Lexer.getTok(); 596 auto TypeName = expectIdent(); 597 if (TypeName.empty()) 598 return true; 599 auto Type = parseType(TypeName); 600 if (!Type) 601 return error("Unknown type in .globaltype directive: ", TypeTok); 602 // Now set this symbol with the correct type. 603 auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName)); 604 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL); 605 WasmSym->setGlobalType( 606 wasm::WasmGlobalType{uint8_t(Type.getValue()), true}); 607 // And emit the directive again. 608 TOut.emitGlobalType(WasmSym); 609 return expect(AsmToken::EndOfStatement, "EOL"); 610 } 611 612 if (DirectiveID.getString() == ".functype") { 613 // This code has to send things to the streamer similar to 614 // WebAssemblyAsmPrinter::EmitFunctionBodyStart. 615 // TODO: would be good to factor this into a common function, but the 616 // assembler and backend really don't share any common code, and this code 617 // parses the locals seperately. 618 auto SymName = expectIdent(); 619 if (SymName.empty()) 620 return true; 621 auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName)); 622 if (CurrentState == Label && WasmSym == LastLabel) { 623 // This .functype indicates a start of a function. 624 if (ensureEmptyNestingStack()) 625 return true; 626 CurrentState = FunctionStart; 627 LastFunctionLabel = LastLabel; 628 push(Function); 629 } 630 auto Signature = make_unique<wasm::WasmSignature>(); 631 if (parseSignature(Signature.get())) 632 return true; 633 WasmSym->setSignature(Signature.get()); 634 addSignature(std::move(Signature)); 635 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION); 636 TOut.emitFunctionType(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() == ".eventtype") { 642 auto SymName = expectIdent(); 643 if (SymName.empty()) 644 return true; 645 auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName)); 646 auto Signature = make_unique<wasm::WasmSignature>(); 647 if (parseRegTypeList(Signature->Params)) 648 return true; 649 WasmSym->setSignature(Signature.get()); 650 addSignature(std::move(Signature)); 651 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_EVENT); 652 TOut.emitEventType(WasmSym); 653 // TODO: backend also calls TOut.emitIndIdx, but that is not implemented. 654 return expect(AsmToken::EndOfStatement, "EOL"); 655 } 656 657 if (DirectiveID.getString() == ".local") { 658 if (CurrentState != FunctionStart) 659 return error(".local directive should follow the start of a function", 660 Lexer.getTok()); 661 SmallVector<wasm::ValType, 4> Locals; 662 if (parseRegTypeList(Locals)) 663 return true; 664 TOut.emitLocal(Locals); 665 CurrentState = FunctionLocals; 666 return expect(AsmToken::EndOfStatement, "EOL"); 667 } 668 669 if (DirectiveID.getString() == ".int8") { 670 if (CheckDataSection()) return true; 671 int64_t V; 672 if (Parser.parseAbsoluteExpression(V)) 673 return error("Cannot parse int8 constant: ", Lexer.getTok()); 674 // TODO: error if value doesn't fit? 675 Out.EmitIntValue(static_cast<uint64_t>(V), 1); 676 return expect(AsmToken::EndOfStatement, "EOL"); 677 } 678 679 if (DirectiveID.getString() == ".asciz") { 680 if (CheckDataSection()) return true; 681 std::string S; 682 if (Parser.parseEscapedString(S)) 683 return error("Cannot parse string constant: ", Lexer.getTok()); 684 Out.EmitBytes(StringRef(S.c_str(), S.length() + 1)); 685 return expect(AsmToken::EndOfStatement, "EOL"); 686 } 687 688 return true; // We didn't process this directive. 689 } 690 691 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned & /*Opcode*/, 692 OperandVector &Operands, MCStreamer &Out, 693 uint64_t &ErrorInfo, 694 bool MatchingInlineAsm) override { 695 MCInst Inst; 696 unsigned MatchResult = 697 MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm); 698 switch (MatchResult) { 699 case Match_Success: { 700 if (CurrentState == FunctionStart) { 701 // This is the first instruction in a function, but we haven't seen 702 // a .local directive yet. The streamer requires locals to be encoded 703 // as a prelude to the instructions, so emit an empty list of locals 704 // here. 705 auto &TOut = reinterpret_cast<WebAssemblyTargetStreamer &>( 706 *Out.getTargetStreamer()); 707 TOut.emitLocal(SmallVector<wasm::ValType, 0>()); 708 } 709 // Fix unknown p2align operands. 710 auto Align = WebAssembly::GetDefaultP2AlignAny(Inst.getOpcode()); 711 if (Align != -1U) { 712 auto &Op0 = Inst.getOperand(0); 713 if (Op0.getImm() == -1) 714 Op0.setImm(Align); 715 } 716 Out.EmitInstruction(Inst, getSTI()); 717 if (CurrentState == EndFunction) { 718 onEndOfFunction(); 719 } else { 720 CurrentState = Instructions; 721 } 722 return false; 723 } 724 case Match_MissingFeature: 725 return Parser.Error( 726 IDLoc, "instruction requires a WASM feature not currently enabled"); 727 case Match_MnemonicFail: 728 return Parser.Error(IDLoc, "invalid instruction"); 729 case Match_NearMisses: 730 return Parser.Error(IDLoc, "ambiguous instruction"); 731 case Match_InvalidTiedOperand: 732 case Match_InvalidOperand: { 733 SMLoc ErrorLoc = IDLoc; 734 if (ErrorInfo != ~0ULL) { 735 if (ErrorInfo >= Operands.size()) 736 return Parser.Error(IDLoc, "too few operands for instruction"); 737 ErrorLoc = Operands[ErrorInfo]->getStartLoc(); 738 if (ErrorLoc == SMLoc()) 739 ErrorLoc = IDLoc; 740 } 741 return Parser.Error(ErrorLoc, "invalid operand for instruction"); 742 } 743 } 744 llvm_unreachable("Implement any new match types added!"); 745 } 746 747 void doBeforeLabelEmit(MCSymbol *Symbol) override { 748 // Start a new section for the next function automatically, since our 749 // object writer expects each function to have its own section. This way 750 // The user can't forget this "convention". 751 auto SymName = Symbol->getName(); 752 if (SymName.startswith(".L")) 753 return; // Local Symbol. 754 auto SecName = ".text." + SymName; 755 auto WS = getContext().getWasmSection(SecName, SectionKind::getText()); 756 getStreamer().SwitchSection(WS); 757 } 758 759 void onEndOfFunction() { 760 // Automatically output a .size directive, so it becomes optional for the 761 // user. 762 if (!LastFunctionLabel) return; 763 auto TempSym = getContext().createLinkerPrivateTempSymbol(); 764 getStreamer().EmitLabel(TempSym); 765 auto Start = MCSymbolRefExpr::create(LastFunctionLabel, getContext()); 766 auto End = MCSymbolRefExpr::create(TempSym, getContext()); 767 auto Expr = 768 MCBinaryExpr::create(MCBinaryExpr::Sub, End, Start, getContext()); 769 getStreamer().emitELFSize(LastFunctionLabel, Expr); 770 } 771 772 void onEndOfFile() override { ensureEmptyNestingStack(); } 773 }; 774 } // end anonymous namespace 775 776 // Force static initialization. 777 extern "C" void LLVMInitializeWebAssemblyAsmParser() { 778 RegisterMCAsmParser<WebAssemblyAsmParser> X(getTheWebAssemblyTarget32()); 779 RegisterMCAsmParser<WebAssemblyAsmParser> Y(getTheWebAssemblyTarget64()); 780 } 781 782 #define GET_REGISTER_MATCHER 783 #define GET_MATCHER_IMPLEMENTATION 784 #include "WebAssemblyGenAsmMatcher.inc" 785