1 //==- WebAssemblyAsmParser.cpp - Assembler for WebAssembly -*- C++ -*-==// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// 10 /// \file 11 /// This file is part of the WebAssembly Assembler. 12 /// 13 /// It contains code to translate a parsed .s file into MCInsts. 14 /// 15 //===----------------------------------------------------------------------===// 16 17 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" 18 #include "MCTargetDesc/WebAssemblyTargetStreamer.h" 19 #include "WebAssembly.h" 20 #include "llvm/MC/MCContext.h" 21 #include "llvm/MC/MCParser/MCTargetAsmParser.h" 22 #include "llvm/MC/MCParser/MCParsedAsmOperand.h" 23 #include "llvm/MC/MCInst.h" 24 #include "llvm/MC/MCInstrInfo.h" 25 #include "llvm/MC/MCSubtargetInfo.h" 26 #include "llvm/MC/MCSymbol.h" 27 #include "llvm/MC/MCStreamer.h" 28 #include "llvm/Support/Endian.h" 29 #include "llvm/Support/TargetRegistry.h" 30 31 using namespace llvm; 32 33 #define DEBUG_TYPE "wasm-asm-parser" 34 35 namespace { 36 37 // We store register types as SimpleValueType to retain SIMD layout 38 // information, but must also be able to supply them as the (unnamed) 39 // register enum from WebAssemblyRegisterInfo.td/.inc. 40 static unsigned MVTToWasmReg(MVT::SimpleValueType Type) { 41 switch(Type) { 42 case MVT::i32: return WebAssembly::I32_0; 43 case MVT::i64: return WebAssembly::I64_0; 44 case MVT::f32: return WebAssembly::F32_0; 45 case MVT::f64: return WebAssembly::F64_0; 46 case MVT::v16i8: return WebAssembly::V128_0; 47 case MVT::v8i16: return WebAssembly::V128_0; 48 case MVT::v4i32: return WebAssembly::V128_0; 49 case MVT::v4f32: return WebAssembly::V128_0; 50 default: return MVT::INVALID_SIMPLE_VALUE_TYPE; 51 } 52 } 53 54 /// WebAssemblyOperand - Instances of this class represent the operands in a 55 /// parsed WASM machine instruction. 56 struct WebAssemblyOperand : public MCParsedAsmOperand { 57 enum KindTy { Token, Local, Stack, Integer, Float, Symbol } Kind; 58 59 SMLoc StartLoc, EndLoc; 60 61 struct TokOp { 62 StringRef Tok; 63 }; 64 65 struct RegOp { 66 // This is a (virtual) local or stack register represented as 0.. 67 unsigned RegNo; 68 // In most targets, the register number also encodes the type, but for 69 // wasm we have to track that seperately since we have an unbounded 70 // number of registers. 71 // This has the unfortunate side effect that we supply a different value 72 // to the table-gen matcher at different times in the process (when it 73 // calls getReg() or addRegOperands(). 74 // TODO: While this works, it feels brittle. and would be nice to clean up. 75 MVT::SimpleValueType Type; 76 }; 77 78 struct IntOp { 79 int64_t Val; 80 }; 81 82 struct FltOp { 83 double Val; 84 }; 85 86 struct SymOp { 87 const MCExpr *Exp; 88 }; 89 90 union { 91 struct TokOp Tok; 92 struct RegOp Reg; 93 struct IntOp Int; 94 struct FltOp Flt; 95 struct SymOp Sym; 96 }; 97 98 WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, TokOp T) 99 : Kind(K), StartLoc(Start), EndLoc(End), Tok(T) {} 100 WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, RegOp R) 101 : Kind(K), StartLoc(Start), EndLoc(End), Reg(R) {} 102 WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, IntOp I) 103 : Kind(K), StartLoc(Start), EndLoc(End), Int(I) {} 104 WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, FltOp F) 105 : Kind(K), StartLoc(Start), EndLoc(End), Flt(F) {} 106 WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, SymOp S) 107 : Kind(K), StartLoc(Start), EndLoc(End), Sym(S) {} 108 109 bool isToken() const override { return Kind == Token; } 110 bool isImm() const override { return Kind == Integer || 111 Kind == Float || 112 Kind == Symbol; } 113 bool isReg() const override { return Kind == Local || Kind == Stack; } 114 bool isMem() const override { return false; } 115 116 unsigned getReg() const override { 117 assert(isReg()); 118 // This is called from the tablegen matcher (MatchInstructionImpl) 119 // where it expects to match the type of register, see RegOp above. 120 return MVTToWasmReg(Reg.Type); 121 } 122 123 StringRef getToken() const { 124 assert(isToken()); 125 return Tok.Tok; 126 } 127 128 SMLoc getStartLoc() const override { return StartLoc; } 129 SMLoc getEndLoc() const override { return EndLoc; } 130 131 void addRegOperands(MCInst &Inst, unsigned N) const { 132 assert(N == 1 && "Invalid number of operands!"); 133 assert(isReg() && "Not a register operand!"); 134 // This is called from the tablegen matcher (MatchInstructionImpl) 135 // where it expects to output the actual register index, see RegOp above. 136 unsigned R = Reg.RegNo; 137 if (Kind == Stack) { 138 // A stack register is represented as a large negative number. 139 // See WebAssemblyRegNumbering::runOnMachineFunction and 140 // getWARegStackId for why this | is needed. 141 R |= INT32_MIN; 142 } 143 Inst.addOperand(MCOperand::createReg(R)); 144 } 145 146 void addImmOperands(MCInst &Inst, unsigned N) const { 147 assert(N == 1 && "Invalid number of operands!"); 148 if (Kind == Integer) 149 Inst.addOperand(MCOperand::createImm(Int.Val)); 150 else if (Kind == Float) 151 Inst.addOperand(MCOperand::createFPImm(Flt.Val)); 152 else if (Kind == Symbol) 153 Inst.addOperand(MCOperand::createExpr(Sym.Exp)); 154 else 155 llvm_unreachable("Should be immediate or symbol!"); 156 } 157 158 void print(raw_ostream &OS) const override { 159 switch (Kind) { 160 case Token: 161 OS << "Tok:" << Tok.Tok; 162 break; 163 case Local: 164 OS << "Loc:" << Reg.RegNo << ":" << static_cast<int>(Reg.Type); 165 break; 166 case Stack: 167 OS << "Stk:" << Reg.RegNo << ":" << static_cast<int>(Reg.Type); 168 break; 169 case Integer: 170 OS << "Int:" << Int.Val; 171 break; 172 case Float: 173 OS << "Flt:" << Flt.Val; 174 break; 175 case Symbol: 176 OS << "Sym:" << Sym.Exp; 177 break; 178 } 179 } 180 }; 181 182 class WebAssemblyAsmParser final : public MCTargetAsmParser { 183 MCAsmParser &Parser; 184 MCAsmLexer &Lexer; 185 // These are for the current function being parsed: 186 // These are vectors since register assignments are so far non-sparse. 187 // Replace by map if necessary. 188 std::vector<MVT::SimpleValueType> LocalTypes; 189 std::vector<MVT::SimpleValueType> StackTypes; 190 MCSymbol *LastLabel; 191 192 public: 193 WebAssemblyAsmParser(const MCSubtargetInfo &sti, MCAsmParser &Parser, 194 const MCInstrInfo &mii, const MCTargetOptions &Options) 195 : MCTargetAsmParser(Options, sti, mii), Parser(Parser), 196 Lexer(Parser.getLexer()), LastLabel(nullptr) { 197 } 198 199 #define GET_ASSEMBLER_HEADER 200 #include "WebAssemblyGenAsmMatcher.inc" 201 202 // TODO: This is required to be implemented, but appears unused. 203 bool ParseRegister(unsigned &/*RegNo*/, SMLoc &/*StartLoc*/, 204 SMLoc &/*EndLoc*/) override { 205 llvm_unreachable("ParseRegister is not implemented."); 206 } 207 208 bool Error(const StringRef &msg, const AsmToken &tok) { 209 return Parser.Error(tok.getLoc(), msg + tok.getString()); 210 } 211 212 bool IsNext(AsmToken::TokenKind Kind) { 213 auto ok = Lexer.is(Kind); 214 if (ok) Parser.Lex(); 215 return ok; 216 } 217 218 bool Expect(AsmToken::TokenKind Kind, const char *KindName) { 219 if (!IsNext(Kind)) 220 return Error(std::string("Expected ") + KindName + ", instead got: ", 221 Lexer.getTok()); 222 return false; 223 } 224 225 MVT::SimpleValueType ParseRegType(const StringRef &RegType) { 226 // Derive type from .param .local decls, or the instruction itself. 227 return StringSwitch<MVT::SimpleValueType>(RegType) 228 .Case("i32", MVT::i32) 229 .Case("i64", MVT::i64) 230 .Case("f32", MVT::f32) 231 .Case("f64", MVT::f64) 232 .Case("i8x16", MVT::v16i8) 233 .Case("i16x8", MVT::v8i16) 234 .Case("i32x4", MVT::v4i32) 235 .Case("f32x4", MVT::v4f32) 236 .Default(MVT::INVALID_SIMPLE_VALUE_TYPE); 237 } 238 239 MVT::SimpleValueType &GetType( 240 std::vector<MVT::SimpleValueType> &Types, size_t i) { 241 Types.resize(std::max(i + 1, Types.size()), MVT::INVALID_SIMPLE_VALUE_TYPE); 242 return Types[i]; 243 } 244 245 bool ParseReg(OperandVector &Operands, StringRef TypePrefix) { 246 if (Lexer.is(AsmToken::Integer)) { 247 auto &Local = Lexer.getTok(); 248 // This is a reference to a local, turn it into a virtual register. 249 auto LocalNo = static_cast<unsigned>(Local.getIntVal()); 250 Operands.push_back(make_unique<WebAssemblyOperand>( 251 WebAssemblyOperand::Local, Local.getLoc(), 252 Local.getEndLoc(), 253 WebAssemblyOperand::RegOp{LocalNo, 254 GetType(LocalTypes, LocalNo)})); 255 Parser.Lex(); 256 } else if (Lexer.is(AsmToken::Identifier)) { 257 auto &StackRegTok = Lexer.getTok(); 258 // These are push/pop/drop pseudo stack registers, which we turn 259 // into virtual registers also. The stackify pass will later turn them 260 // back into implicit stack references if possible. 261 auto StackReg = StackRegTok.getString(); 262 auto StackOp = StackReg.take_while([](char c) { return isalpha(c); }); 263 auto Reg = StackReg.drop_front(StackOp.size()); 264 unsigned long long ParsedRegNo = 0; 265 if (!Reg.empty() && getAsUnsignedInteger(Reg, 10, ParsedRegNo)) 266 return Error("Cannot parse stack register index: ", StackRegTok); 267 unsigned RegNo = static_cast<unsigned>(ParsedRegNo); 268 if (StackOp == "push") { 269 // This defines a result, record register type. 270 auto RegType = ParseRegType(TypePrefix); 271 GetType(StackTypes, RegNo) = RegType; 272 Operands.push_back(make_unique<WebAssemblyOperand>( 273 WebAssemblyOperand::Stack, 274 StackRegTok.getLoc(), 275 StackRegTok.getEndLoc(), 276 WebAssemblyOperand::RegOp{RegNo, RegType})); 277 } else if (StackOp == "pop") { 278 // This uses a previously defined stack value. 279 auto RegType = GetType(StackTypes, RegNo); 280 Operands.push_back(make_unique<WebAssemblyOperand>( 281 WebAssemblyOperand::Stack, 282 StackRegTok.getLoc(), 283 StackRegTok.getEndLoc(), 284 WebAssemblyOperand::RegOp{RegNo, RegType})); 285 } else if (StackOp == "drop") { 286 // This operand will be dropped, since it is part of an instruction 287 // whose result is void. 288 } else { 289 return Error("Unknown stack register prefix: ", StackRegTok); 290 } 291 Parser.Lex(); 292 } else { 293 return Error( 294 "Expected identifier/integer following $, instead got: ", 295 Lexer.getTok()); 296 } 297 IsNext(AsmToken::Equal); 298 return false; 299 } 300 301 void ParseSingleInteger(bool IsNegative, OperandVector &Operands) { 302 auto &Int = Lexer.getTok(); 303 int64_t Val = Int.getIntVal(); 304 if (IsNegative) Val = -Val; 305 Operands.push_back(make_unique<WebAssemblyOperand>( 306 WebAssemblyOperand::Integer, Int.getLoc(), 307 Int.getEndLoc(), WebAssemblyOperand::IntOp{Val})); 308 Parser.Lex(); 309 } 310 311 bool ParseOperandStartingWithInteger(bool IsNegative, 312 OperandVector &Operands, 313 StringRef InstType) { 314 ParseSingleInteger(IsNegative, Operands); 315 if (Lexer.is(AsmToken::LParen)) { 316 // Parse load/store operands of the form: offset($reg)align 317 auto &LParen = Lexer.getTok(); 318 Operands.push_back( 319 make_unique<WebAssemblyOperand>(WebAssemblyOperand::Token, 320 LParen.getLoc(), 321 LParen.getEndLoc(), 322 WebAssemblyOperand::TokOp{ 323 LParen.getString()})); 324 Parser.Lex(); 325 if (Expect(AsmToken::Dollar, "register")) return true; 326 if (ParseReg(Operands, InstType)) return true; 327 auto &RParen = Lexer.getTok(); 328 Operands.push_back( 329 make_unique<WebAssemblyOperand>(WebAssemblyOperand::Token, 330 RParen.getLoc(), 331 RParen.getEndLoc(), 332 WebAssemblyOperand::TokOp{ 333 RParen.getString()})); 334 if (Expect(AsmToken::RParen, ")")) return true; 335 if (Lexer.is(AsmToken::Integer)) { 336 ParseSingleInteger(false, Operands); 337 } else { 338 // Alignment not specified. 339 // FIXME: correctly derive a default from the instruction. 340 Operands.push_back(make_unique<WebAssemblyOperand>( 341 WebAssemblyOperand::Integer, RParen.getLoc(), 342 RParen.getEndLoc(), WebAssemblyOperand::IntOp{0})); 343 } 344 } 345 return false; 346 } 347 348 bool ParseInstruction(ParseInstructionInfo &/*Info*/, StringRef Name, 349 SMLoc NameLoc, OperandVector &Operands) override { 350 Operands.push_back( 351 make_unique<WebAssemblyOperand>(WebAssemblyOperand::Token, NameLoc, 352 SMLoc::getFromPointer( 353 NameLoc.getPointer() + Name.size()), 354 WebAssemblyOperand::TokOp{ 355 StringRef(NameLoc.getPointer(), 356 Name.size())})); 357 auto NamePair = Name.split('.'); 358 // If no '.', there is no type prefix. 359 if (NamePair.second.empty()) std::swap(NamePair.first, NamePair.second); 360 while (Lexer.isNot(AsmToken::EndOfStatement)) { 361 auto &Tok = Lexer.getTok(); 362 switch (Tok.getKind()) { 363 case AsmToken::Dollar: { 364 Parser.Lex(); 365 if (ParseReg(Operands, NamePair.first)) return true; 366 break; 367 } 368 case AsmToken::Identifier: { 369 auto &Id = Lexer.getTok(); 370 const MCExpr *Val; 371 SMLoc End; 372 if (Parser.parsePrimaryExpr(Val, End)) 373 return Error("Cannot parse symbol: ", Lexer.getTok()); 374 Operands.push_back(make_unique<WebAssemblyOperand>( 375 WebAssemblyOperand::Symbol, Id.getLoc(), 376 Id.getEndLoc(), WebAssemblyOperand::SymOp{Val})); 377 break; 378 } 379 case AsmToken::Minus: 380 Parser.Lex(); 381 if (Lexer.isNot(AsmToken::Integer)) 382 return Error("Expected integer instead got: ", Lexer.getTok()); 383 if (ParseOperandStartingWithInteger(true, Operands, NamePair.first)) 384 return true; 385 break; 386 case AsmToken::Integer: 387 if (ParseOperandStartingWithInteger(false, Operands, NamePair.first)) 388 return true; 389 break; 390 case AsmToken::Real: { 391 double Val; 392 if (Tok.getString().getAsDouble(Val, false)) 393 return Error("Cannot parse real: ", Tok); 394 Operands.push_back(make_unique<WebAssemblyOperand>( 395 WebAssemblyOperand::Float, Tok.getLoc(), 396 Tok.getEndLoc(), WebAssemblyOperand::FltOp{Val})); 397 Parser.Lex(); 398 break; 399 } 400 default: 401 return Error("Unexpected token in operand: ", Tok); 402 } 403 if (Lexer.isNot(AsmToken::EndOfStatement)) { 404 if (Expect(AsmToken::Comma, ",")) return true; 405 } 406 } 407 Parser.Lex(); 408 // Call instructions are vararg, but the tablegen matcher doesn't seem to 409 // support that, so for now we strip these extra operands. 410 // This is problematic if these arguments are not simple $pop stack 411 // registers, since e.g. a local register would get lost, so we check for 412 // this. This can be the case when using -disable-wasm-explicit-locals 413 // which currently s2wasm requires. 414 // TODO: Instead, we can move this code to MatchAndEmitInstruction below and 415 // actually generate get_local instructions on the fly. 416 // Or even better, improve the matcher to support vararg? 417 auto IsIndirect = NamePair.second == "call_indirect"; 418 if (IsIndirect || NamePair.second == "call") { 419 // Figure out number of fixed operands from the instruction. 420 size_t CallOperands = 1; // The name token. 421 if (!IsIndirect) CallOperands++; // The function index. 422 if (!NamePair.first.empty()) CallOperands++; // The result register. 423 if (Operands.size() > CallOperands) { 424 // Ensure operands we drop are all $pop. 425 for (size_t I = CallOperands; I < Operands.size(); I++) { 426 auto Operand = 427 reinterpret_cast<WebAssemblyOperand *>(Operands[I].get()); 428 if (Operand->Kind != WebAssemblyOperand::Stack) 429 Parser.Error(NameLoc, 430 "Call instruction has non-stack arguments, if this code was " 431 "generated with -disable-wasm-explicit-locals please remove it"); 432 } 433 // Drop unneeded operands. 434 Operands.resize(CallOperands); 435 } 436 } 437 // Block instructions require a signature index, but these are missing in 438 // assembly, so we add a dummy one explicitly (since we have no control 439 // over signature tables here, we assume these will be regenerated when 440 // the wasm module is generated). 441 if (NamePair.second == "block" || NamePair.second == "loop") { 442 Operands.push_back(make_unique<WebAssemblyOperand>( 443 WebAssemblyOperand::Integer, NameLoc, 444 NameLoc, WebAssemblyOperand::IntOp{-1})); 445 } 446 // These don't specify the type, which has to derived from the local index. 447 if (NamePair.second == "get_local" || NamePair.second == "tee_local") { 448 if (Operands.size() >= 3 && Operands[1]->isReg() && 449 Operands[2]->isImm()) { 450 auto Op1 = reinterpret_cast<WebAssemblyOperand *>(Operands[1].get()); 451 auto Op2 = reinterpret_cast<WebAssemblyOperand *>(Operands[2].get()); 452 auto Type = GetType(LocalTypes, static_cast<size_t>(Op2->Int.Val)); 453 Op1->Reg.Type = Type; 454 GetType(StackTypes, Op1->Reg.RegNo) = Type; 455 } 456 } 457 return false; 458 } 459 460 void onLabelParsed(MCSymbol *Symbol) override { 461 LastLabel = Symbol; 462 } 463 464 bool ParseDirective(AsmToken DirectiveID) override { 465 assert(DirectiveID.getKind() == AsmToken::Identifier); 466 auto &Out = getStreamer(); 467 auto &TOut = reinterpret_cast<WebAssemblyTargetStreamer &>( 468 *Out.getTargetStreamer()); 469 // TODO: we're just parsing the subset of directives we're interested in, 470 // and ignoring ones we don't recognise. We should ideally verify 471 // all directives here. 472 if (DirectiveID.getString() == ".type") { 473 // This could be the start of a function, check if followed by 474 // "label,@function" 475 if (!(IsNext(AsmToken::Identifier) && 476 IsNext(AsmToken::Comma) && 477 IsNext(AsmToken::At) && 478 Lexer.is(AsmToken::Identifier))) 479 return Error("Expected label,@type declaration, got: ", Lexer.getTok()); 480 if (Lexer.getTok().getString() == "function") { 481 // Track locals from start of function. 482 LocalTypes.clear(); 483 StackTypes.clear(); 484 } 485 Parser.Lex(); 486 //Out.EmitSymbolAttribute(??, MCSA_ELF_TypeFunction); 487 } else if (DirectiveID.getString() == ".param" || 488 DirectiveID.getString() == ".local") { 489 // Track the number of locals, needed for correct virtual register 490 // assignment elsewhere. 491 // Also output a directive to the streamer. 492 std::vector<MVT> Params; 493 std::vector<MVT> Locals; 494 while (Lexer.is(AsmToken::Identifier)) { 495 auto RegType = ParseRegType(Lexer.getTok().getString()); 496 if (RegType == MVT::INVALID_SIMPLE_VALUE_TYPE) return true; 497 LocalTypes.push_back(RegType); 498 if (DirectiveID.getString() == ".param") { 499 Params.push_back(RegType); 500 } else { 501 Locals.push_back(RegType); 502 } 503 Parser.Lex(); 504 if (!IsNext(AsmToken::Comma)) break; 505 } 506 assert(LastLabel); 507 TOut.emitParam(LastLabel, Params); 508 TOut.emitLocal(Locals); 509 } else { 510 // For now, ignore anydirective we don't recognize: 511 while (Lexer.isNot(AsmToken::EndOfStatement)) Parser.Lex(); 512 } 513 return Expect(AsmToken::EndOfStatement, "EOL"); 514 } 515 516 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &/*Opcode*/, 517 OperandVector &Operands, 518 MCStreamer &Out, uint64_t &ErrorInfo, 519 bool MatchingInlineAsm) override { 520 MCInst Inst; 521 unsigned MatchResult = 522 MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm); 523 switch (MatchResult) { 524 case Match_Success: { 525 Out.EmitInstruction(Inst, getSTI()); 526 return false; 527 } 528 case Match_MissingFeature: 529 return Parser.Error(IDLoc, 530 "instruction requires a WASM feature not currently enabled"); 531 case Match_MnemonicFail: 532 return Parser.Error(IDLoc, "invalid instruction"); 533 case Match_NearMisses: 534 return Parser.Error(IDLoc, "ambiguous instruction"); 535 case Match_InvalidTiedOperand: 536 case Match_InvalidOperand: { 537 SMLoc ErrorLoc = IDLoc; 538 if (ErrorInfo != ~0ULL) { 539 if (ErrorInfo >= Operands.size()) 540 return Parser.Error(IDLoc, "too few operands for instruction"); 541 ErrorLoc = Operands[ErrorInfo]->getStartLoc(); 542 if (ErrorLoc == SMLoc()) 543 ErrorLoc = IDLoc; 544 } 545 return Parser.Error(ErrorLoc, "invalid operand for instruction"); 546 } 547 } 548 llvm_unreachable("Implement any new match types added!"); 549 } 550 }; 551 } // end anonymous namespace 552 553 // Force static initialization. 554 extern "C" void LLVMInitializeWebAssemblyAsmParser() { 555 RegisterMCAsmParser<WebAssemblyAsmParser> X(getTheWebAssemblyTarget32()); 556 RegisterMCAsmParser<WebAssemblyAsmParser> Y(getTheWebAssemblyTarget64()); 557 } 558 559 #define GET_REGISTER_MATCHER 560 #define GET_MATCHER_IMPLEMENTATION 561 #include "WebAssemblyGenAsmMatcher.inc" 562