36 #define DEBUG_TYPE "wasm-asm-parser" 45 SMLoc StartLoc, EndLoc;
64 std::vector<unsigned>
List;
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() {}
86 ~WebAssemblyOperand() {
91 bool isToken()
const override {
return Kind == Token; }
92 bool isImm()
const override {
return Kind ==
Integer || Kind ==
Symbol; }
93 bool isFPImm()
const {
return Kind ==
Float; }
94 bool isMem()
const override {
return false; }
95 bool isReg()
const override {
return false; }
96 bool isBrList()
const {
return Kind == BrList; }
98 unsigned getReg()
const override {
108 SMLoc getStartLoc()
const override {
return StartLoc; }
109 SMLoc getEndLoc()
const override {
return EndLoc; }
111 void addRegOperands(
MCInst &,
unsigned)
const {
116 void addImmOperands(
MCInst &Inst,
unsigned N)
const {
117 assert(N == 1 &&
"Invalid number of operands!");
126 void addFPImmOperands(
MCInst &Inst,
unsigned N)
const {
127 assert(N == 1 &&
"Invalid number of operands!");
134 void addBrListOperands(
MCInst &Inst,
unsigned N)
const {
135 assert(N == 1 && isBrList() &&
"Invalid BrList!");
136 for (
auto Br : BrL.List)
143 OS <<
"Tok:" << Tok.Tok;
146 OS <<
"Int:" <<
Int.Val;
149 OS <<
"Flt:" << Flt.Val;
152 OS <<
"Sym:" << Sym.Exp;
155 OS <<
"BrList:" << BrL.List.size();
166 std::vector<std::unique_ptr<wasm::WasmSignature>> Signatures;
182 } CurrentState = FileStart;
194 std::vector<NestingType> NestingStack;
199 MCSymbol *LastFunctionLabel =
nullptr;
206 setAvailableFeatures(ComputeAvailableFeatures(STI.
getFeatureBits()));
209 #define GET_ASSEMBLER_HEADER 210 #include "WebAssemblyGenAsmMatcher.inc" 213 bool ParseRegister(
unsigned & ,
SMLoc & ,
226 void addSignature(std::unique_ptr<wasm::WasmSignature> &&Sig) {
227 Signatures.push_back(std::move(Sig));
230 std::pair<StringRef, StringRef> nestingString(NestingType NT) {
233 return {
"function",
"end_function"};
235 return {
"block",
"end_block"};
237 return {
"loop",
"end_loop"};
239 return {
"try",
"end_try"};
241 return {
"if",
"end_if"};
243 return {
"else",
"end_if"};
249 void push(NestingType NT) { NestingStack.push_back(NT); }
251 bool pop(
StringRef Ins, NestingType NT1, NestingType NT2 = Undefined) {
252 if (NestingStack.empty())
253 return error(
Twine(
"End of block construct with no start: ") +
Ins);
254 auto Top = NestingStack.back();
255 if (Top != NT1 && Top != NT2)
256 return error(
Twine(
"Block construct type mismatch, expected: ") +
257 nestingString(Top).
second +
", instead got: " + Ins);
258 NestingStack.pop_back();
262 bool ensureEmptyNestingStack() {
263 auto Err = !NestingStack.empty();
264 while (!NestingStack.empty()) {
265 error(
Twine(
"Unmatched block construct(s) at function end: ") +
266 nestingString(NestingStack.back()).
first);
267 NestingStack.pop_back();
273 auto Ok = Lexer.
is(Kind);
281 return error(std::string(
"Expected ") + KindName +
", instead got: ",
288 error(
"Expected identifier, got: ", Lexer.
getTok());
307 if (Type ==
"v128" || Type ==
"i8x16" || Type ==
"i16x8" ||
308 Type ==
"i32x4" || Type ==
"i64x2" || Type ==
"f32x4" ||
311 if (Type ==
"exnref")
343 auto &Int = Lexer.
getTok();
344 int64_t Val = Int.getIntVal();
347 Operands.
push_back(std::make_unique<WebAssemblyOperand>(
349 WebAssemblyOperand::IntOp{Val}));
353 bool parseSingleFloat(
bool IsNegative,
OperandVector &Operands) {
354 auto &Flt = Lexer.
getTok();
356 if (Flt.getString().getAsDouble(Val,
false))
357 return error(
"Cannot parse real: ", Flt);
360 Operands.
push_back(std::make_unique<WebAssemblyOperand>(
362 WebAssemblyOperand::FltOp{Val}));
367 bool parseSpecialFloatMaybe(
bool IsNegative,
OperandVector &Operands) {
370 auto &Flt = Lexer.
getTok();
373 if (S.compare_lower(
"infinity") == 0) {
374 Val = std::numeric_limits<double>::infinity();
375 }
else if (S.compare_lower(
"nan") == 0) {
376 Val = std::numeric_limits<double>::quiet_NaN();
382 Operands.
push_back(std::make_unique<WebAssemblyOperand>(
384 WebAssemblyOperand::FltOp{Val}));
394 if (IsLoadStore || IsAtomic) {
397 auto Id = expectIdent();
399 return error(
"Expected p2align, instead got: " +
Id);
403 return error(
"Expected integer constant");
404 parseSingleInteger(
false, Operands);
410 auto Tok = Lexer.
getTok();
411 Operands.
push_back(std::make_unique<WebAssemblyOperand>(
413 WebAssemblyOperand::IntOp{-1}));
421 Operands.
push_back(std::make_unique<WebAssemblyOperand>(
423 WebAssemblyOperand::IntOp{
static_cast<int64_t
>(
BT)}));
436 auto &Sep = Lexer.
getTok();
437 if (Sep.getLoc().getPointer() != Name.
end() ||
446 Id.getLoc().getPointer() != Name.
end())
447 return error(
"Incomplete instruction name: ",
Id);
453 Operands.
push_back(std::make_unique<WebAssemblyOperand>(
455 WebAssemblyOperand::TokOp{Name}));
459 bool ExpectBlockType =
false;
460 bool ExpectFuncType =
false;
461 if (Name ==
"block") {
463 ExpectBlockType =
true;
464 }
else if (Name ==
"loop") {
466 ExpectBlockType =
true;
467 }
else if (Name ==
"try") {
469 ExpectBlockType =
true;
470 }
else if (Name ==
"if") {
472 ExpectBlockType =
true;
473 }
else if (Name ==
"else") {
477 }
else if (Name ==
"catch") {
481 }
else if (Name ==
"end_if") {
484 }
else if (Name ==
"end_try") {
487 }
else if (Name ==
"end_loop") {
490 }
else if (Name ==
"end_block") {
491 if (pop(Name, Block))
493 }
else if (Name ==
"end_function") {
494 ensureLocals(getStreamer());
495 CurrentState = EndFunction;
496 if (pop(Name,
Function) || ensureEmptyNestingStack())
498 }
else if (Name ==
"call_indirect" || Name ==
"return_call_indirect") {
499 ExpectFuncType =
true;
507 auto Loc = Parser.
getTok();
508 auto Signature = std::make_unique<wasm::WasmSignature>();
509 if (parseSignature(Signature.get()))
512 ExpectBlockType =
false;
513 auto &Ctx = getStreamer().getContext();
515 MCSymbol *Sym = Ctx.createTempSymbol(
"typeindex",
true);
516 auto *WasmSym = cast<MCSymbolWasm>(Sym);
517 WasmSym->setSignature(Signature.get());
518 addSignature(std::move(Signature));
522 Operands.
push_back(std::make_unique<WebAssemblyOperand>(
524 WebAssemblyOperand::SymOp{Expr}));
528 auto &Tok = Lexer.
getTok();
531 if (!parseSpecialFloatMaybe(
false, Operands))
534 if (ExpectBlockType) {
536 auto BT = parseBlockType(
Id.getString());
538 return error(
"Unknown block type: ",
Id);
539 addBlockTypeOperand(Operands, NameLoc, BT);
546 return error(
"Cannot parse symbol: ", Lexer.
getTok());
547 Operands.
push_back(std::make_unique<WebAssemblyOperand>(
549 WebAssemblyOperand::SymOp{Val}));
550 if (checkForP2AlignIfLoadStore(Operands, Name))
558 parseSingleInteger(
true, Operands);
559 if (checkForP2AlignIfLoadStore(Operands, Name))
562 if (parseSingleFloat(
true, Operands))
564 }
else if (!parseSpecialFloatMaybe(
true, Operands)) {
566 return error(
"Expected numeric constant instead got: ",
571 parseSingleInteger(
false, Operands);
572 if (checkForP2AlignIfLoadStore(Operands, Name))
576 if (parseSingleFloat(
false, Operands))
582 auto Op = std::make_unique<WebAssemblyOperand>(
596 return error(
"Unexpected token in operand: ", Tok);
603 if (ExpectBlockType && Operands.
size() == 1) {
613 CurrentState = Label;
619 if (parseRegTypeList(Signature->
Params))
627 if (parseRegTypeList(Signature->
Returns))
634 bool CheckDataSection() {
635 if (CurrentState != DataSection) {
636 auto WS = cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
637 if (WS && WS->getKind().isText())
638 return error(
"data directive must occur in a data segment: ",
641 CurrentState = DataSection;
648 bool ParseDirective(
AsmToken DirectiveID)
override {
656 auto &Out = getStreamer();
659 auto &Ctx = Out.getContext();
663 if (DirectiveID.
getString() ==
".globaltype") {
664 auto SymName = expectIdent();
669 auto TypeTok = Lexer.
getTok();
675 return error(
"Unknown type in .globaltype directive: ", TypeTok);
677 auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
679 WasmSym->setGlobalType(
682 TOut.emitGlobalType(WasmSym);
686 if (DirectiveID.
getString() ==
".functype") {
692 auto SymName = expectIdent();
695 auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
696 if (CurrentState == Label && WasmSym == LastLabel) {
698 if (ensureEmptyNestingStack())
700 CurrentState = FunctionStart;
701 LastFunctionLabel = LastLabel;
704 auto Signature = std::make_unique<wasm::WasmSignature>();
705 if (parseSignature(Signature.get()))
707 WasmSym->setSignature(Signature.get());
708 addSignature(std::move(Signature));
710 TOut.emitFunctionType(WasmSym);
715 if (DirectiveID.
getString() ==
".export_name") {
716 auto SymName = expectIdent();
721 auto ExportName = expectIdent();
722 auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
723 WasmSym->setExportName(ExportName);
724 TOut.emitExportName(WasmSym, ExportName);
727 if (DirectiveID.
getString() ==
".import_module") {
728 auto SymName = expectIdent();
733 auto ImportModule = expectIdent();
734 auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
735 WasmSym->setImportModule(ImportModule);
736 TOut.emitImportModule(WasmSym, ImportModule);
739 if (DirectiveID.
getString() ==
".import_name") {
740 auto SymName = expectIdent();
745 auto ImportName = expectIdent();
746 auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
747 WasmSym->setImportName(ImportName);
748 TOut.emitImportName(WasmSym, ImportName);
751 if (DirectiveID.
getString() ==
".eventtype") {
752 auto SymName = expectIdent();
755 auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
756 auto Signature = std::make_unique<wasm::WasmSignature>();
757 if (parseRegTypeList(Signature->Params))
759 WasmSym->setSignature(Signature.get());
760 addSignature(std::move(Signature));
762 TOut.emitEventType(WasmSym);
767 if (DirectiveID.
getString() ==
".local") {
768 if (CurrentState != FunctionStart)
769 return error(
".local directive should follow the start of a function",
772 if (parseRegTypeList(Locals))
774 TOut.emitLocal(Locals);
775 CurrentState = FunctionLocals;
779 if (DirectiveID.
getString() ==
".int8" ||
783 if (CheckDataSection())
return true;
787 return error(
"Cannot parse .int expression: ", Lexer.
getTok());
790 Out.EmitValue(Val, NumBits / 8, End);
794 if (DirectiveID.
getString() ==
".asciz") {
795 if (CheckDataSection())
return true;
798 return error(
"Cannot parse string constant: ", Lexer.
getTok());
799 Out.EmitBytes(
StringRef(S.c_str(), S.length() + 1));
808 if (CurrentState == FunctionStart) {
815 CurrentState = FunctionLocals;
819 bool MatchAndEmitInstruction(
SMLoc IDLoc,
unsigned & ,
822 bool MatchingInlineAsm)
override {
825 unsigned MatchResult =
826 MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
827 switch (MatchResult) {
828 case Match_Success: {
834 if (Op0.getImm() == -1)
838 if (CurrentState == EndFunction) {
841 CurrentState = Instructions;
845 case Match_MissingFeature:
847 IDLoc,
"instruction requires a WASM feature not currently enabled");
848 case Match_MnemonicFail:
849 return Parser.
Error(IDLoc,
"invalid instruction");
850 case Match_NearMisses:
851 return Parser.
Error(IDLoc,
"ambiguous instruction");
852 case Match_InvalidTiedOperand:
853 case Match_InvalidOperand: {
854 SMLoc ErrorLoc = IDLoc;
855 if (ErrorInfo != ~0ULL) {
856 if (ErrorInfo >= Operands.
size())
857 return Parser.
Error(IDLoc,
"too few operands for instruction");
858 ErrorLoc = Operands[ErrorInfo]->getStartLoc();
859 if (ErrorLoc ==
SMLoc())
862 return Parser.
Error(ErrorLoc,
"invalid operand for instruction");
868 void doBeforeLabelEmit(
MCSymbol *Symbol)
override {
872 auto SymName = Symbol->
getName();
873 if (SymName.startswith(
".L"))
876 auto CWS = cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
877 if (!CWS || !CWS->getKind().isText())
879 auto SecName =
".text." + SymName;
881 getStreamer().SwitchSection(WS);
884 void onEndOfFunction() {
887 if (!LastFunctionLabel)
return;
888 auto TempSym = getContext().createLinkerPrivateTempSymbol();
889 getStreamer().EmitLabel(TempSym);
894 getStreamer().emitELFSize(LastFunctionLabel, Expr);
897 void onEndOfFile()
override { ensureEmptyNestingStack(); }
907 #define GET_REGISTER_MATCHER 908 #define GET_MATCHER_IMPLEMENTATION 909 #include "WebAssemblyGenAsmMatcher.inc" static bool isReg(const MCInst &MI, unsigned OpNo)
const AsmToken & getTok() const
Get the current (last) lexed token.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
StringRef getString() const
Get the string for the current token, this includes all characters (for example, the quotes on string...
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
This class represents lattice values for constants.
bool is(AsmToken::TokenKind K) const
Check if the current token has kind K.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Generic assembler parser interface, for use by target specific assembly parsers.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
static MCOperand createExpr(const MCExpr *Val)
MCTargetAsmParser - Generic interface to target specific assembly parsers.
void push_back(const T &Elt)
virtual const AsmToken & Lex()=0
Get the next AsmToken in the stream, possibly handling file inclusion first.
const AsmToken & getTok() const
Get the current AsmToken from the stream.
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end...
virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI)
Emit the given Instruction into the current section.
StringSwitch & Case(StringLiteral S, T Value)
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
This file registers the WebAssembly target.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
const FeatureBitset & getFeatureBits() const
Generic assembler lexer interface, for use by target specific assembly lexers.
LLVM_NODISCARD StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Base class for the full range of assembler expressions which are needed for parsing.
SmallVector< ValType, 1 > Returns
LLVM_NODISCARD R Default(T Value)
Target independent representation for an assembler token.
mir Rename Register Operands
static bool isMem(const MachineInstr &MI, unsigned Op)
MCParsedAsmOperand - This abstract class represents a source-level assembly instruction operand...
virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc)=0
Parse an arbitrary expression.
SmallVector< ValType, 4 > Params
std::pair< StringRef, StringRef > getToken(StringRef Source, StringRef Delimiters=" \\\)
getToken - This function extracts one token from source, ignoring any leading characters that appear ...
RegisterMCAsmParser - Helper template for registering a target specific assembly parser, for use in the target machine initialization function.
LLVM_NODISCARD size_t size() const
size - Get the string size.
virtual bool parseEscapedString(std::string &Data)=0
Parse the current token as a string which may include escaped characters and return the string conten...
Instances of this class represent a single low-level machine instruction.
static const MCBinaryExpr * create(Opcode Op, const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
WebAssembly-specific streamer interface, to implement support WebAssembly-specific assembly directive...
const char * getPointer() const
A switch()-like statement whose cases are string literals.
Streaming machine code generation interface.
MCTargetStreamer * getTargetStreamer()
The instances of the Type class are immutable: once they are created, they are never changed...
This file provides WebAssembly-specific target descriptions.
Interface to description of machine instruction set.
LLVM_NODISCARD size_t find(char C, size_t From=0) const
Search for the first character C in the string.
virtual MCAsmLexer & getLexer()=0
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
int64_t getIntVal() const
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
bool Error(SMLoc L, const Twine &Msg, SMRange Range=None)
Return an error at the location L, with the message Msg.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This struct is a compact representation of a valid (non-zero power of two) alignment.
This file declares WebAssembly-specific target streamer classes.
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
const MCOperand & getOperand(unsigned i) const
#define LLVM_EXTERNAL_VISIBILITY
static MCOperand createFPImm(double Val)
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyAsmParser()
static unsigned getReg(const void *D, unsigned RC, unsigned RegNo)
Base class for user error types.
static SMLoc getFromPointer(const char *Ptr)
Represents a single loop in the control flow graph.
BlockType
Used as immediate MachineOperands for block signatures.
Generic base class for all target subtargets.
bool isNot(AsmToken::TokenKind K) const
Check if the current token has kind K.
unsigned GetDefaultP2AlignAny(unsigned Opc)
Return the default p2align value for a load or store with the given opcode.
StringRef getName() const
getName - Get the symbol name.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
virtual void emitLocal(ArrayRef< wasm::ValType > Types)=0
.local
This class implements an extremely fast bulk output stream that can only output to a stream...
void addOperand(const MCOperand &Op)
StringRef - Represent a constant reference to a string, i.e.
Target & getTheWebAssemblyTarget32()
Type * parseType(StringRef Asm, SMDiagnostic &Err, const Module &M, const SlotMapping *Slots=nullptr)
Parse a type in the given string.
Represents a location in source code.
unsigned getOpcode() const
Target & getTheWebAssemblyTarget64()
static MCOperand createImm(int64_t Val)
TokenKind getKind() const
static SectionKind getText()