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/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/MCStreamer.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/MC/MCSymbolWasm.h"
29 #include "llvm/Support/Endian.h"
30 #include "llvm/Support/TargetRegistry.h"
31 
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "wasm-asm-parser"
35 
36 namespace {
37 
38 /// WebAssemblyOperand - Instances of this class represent the operands in a
39 /// parsed WASM machine instruction.
40 struct WebAssemblyOperand : public MCParsedAsmOperand {
41   enum KindTy { Token, Integer, Float, Symbol } Kind;
42 
43   SMLoc StartLoc, EndLoc;
44 
45   struct TokOp {
46     StringRef Tok;
47   };
48 
49   struct IntOp {
50     int64_t Val;
51   };
52 
53   struct FltOp {
54     double Val;
55   };
56 
57   struct SymOp {
58     const MCExpr *Exp;
59   };
60 
61   union {
62     struct TokOp Tok;
63     struct IntOp Int;
64     struct FltOp Flt;
65     struct SymOp Sym;
66   };
67 
68   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, TokOp T)
69       : Kind(K), StartLoc(Start), EndLoc(End), Tok(T) {}
70   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, IntOp I)
71       : Kind(K), StartLoc(Start), EndLoc(End), Int(I) {}
72   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, FltOp F)
73       : Kind(K), StartLoc(Start), EndLoc(End), Flt(F) {}
74   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, SymOp S)
75       : Kind(K), StartLoc(Start), EndLoc(End), Sym(S) {}
76 
77   bool isToken() const override { return Kind == Token; }
78   bool isImm() const override {
79     return Kind == Integer || Kind == Float || Kind == Symbol;
80   }
81   bool isMem() const override { return false; }
82   bool isReg() const override { return false; }
83 
84   unsigned getReg() const override {
85     llvm_unreachable("Assembly inspects a register operand");
86     return 0;
87   }
88 
89   StringRef getToken() const {
90     assert(isToken());
91     return Tok.Tok;
92   }
93 
94   SMLoc getStartLoc() const override { return StartLoc; }
95   SMLoc getEndLoc() const override { return EndLoc; }
96 
97   void addRegOperands(MCInst &, unsigned) const {
98     // Required by the assembly matcher.
99     llvm_unreachable("Assembly matcher creates register operands");
100   }
101 
102   void addImmOperands(MCInst &Inst, unsigned N) const {
103     assert(N == 1 && "Invalid number of operands!");
104     if (Kind == Integer)
105       Inst.addOperand(MCOperand::createImm(Int.Val));
106     else if (Kind == Float)
107       Inst.addOperand(MCOperand::createFPImm(Flt.Val));
108     else if (Kind == Symbol)
109       Inst.addOperand(MCOperand::createExpr(Sym.Exp));
110     else
111       llvm_unreachable("Should be immediate or symbol!");
112   }
113 
114   void print(raw_ostream &OS) const override {
115     switch (Kind) {
116     case Token:
117       OS << "Tok:" << Tok.Tok;
118       break;
119     case Integer:
120       OS << "Int:" << Int.Val;
121       break;
122     case Float:
123       OS << "Flt:" << Flt.Val;
124       break;
125     case Symbol:
126       OS << "Sym:" << Sym.Exp;
127       break;
128     }
129   }
130 };
131 
132 class WebAssemblyAsmParser final : public MCTargetAsmParser {
133   MCAsmParser &Parser;
134   MCAsmLexer &Lexer;
135   MCSymbolWasm *LastSymbol;
136 
137 public:
138   WebAssemblyAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
139                        const MCInstrInfo &MII, const MCTargetOptions &Options)
140       : MCTargetAsmParser(Options, STI, MII), Parser(Parser),
141         Lexer(Parser.getLexer()), LastSymbol(nullptr) {
142     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
143   }
144 
145 #define GET_ASSEMBLER_HEADER
146 #include "WebAssemblyGenAsmMatcher.inc"
147 
148   // TODO: This is required to be implemented, but appears unused.
149   bool ParseRegister(unsigned & /*RegNo*/, SMLoc & /*StartLoc*/,
150                      SMLoc & /*EndLoc*/) override {
151     llvm_unreachable("ParseRegister is not implemented.");
152   }
153 
154   bool Error(const StringRef &msg, const AsmToken &tok) {
155     return Parser.Error(tok.getLoc(), msg + tok.getString());
156   }
157 
158   bool IsNext(AsmToken::TokenKind Kind) {
159     auto ok = Lexer.is(Kind);
160     if (ok)
161       Parser.Lex();
162     return ok;
163   }
164 
165   bool Expect(AsmToken::TokenKind Kind, const char *KindName) {
166     if (!IsNext(Kind))
167       return Error(std::string("Expected ") + KindName + ", instead got: ",
168                    Lexer.getTok());
169     return false;
170   }
171 
172 
173   std::pair<MVT::SimpleValueType, unsigned>
174   ParseRegType(const StringRef &RegType) {
175     // Derive type from .param .local decls, or the instruction itself.
176     return StringSwitch<std::pair<MVT::SimpleValueType, unsigned>>(RegType)
177         .Case("i32", {MVT::i32, wasm::WASM_TYPE_I32})
178         .Case("i64", {MVT::i64, wasm::WASM_TYPE_I64})
179         .Case("f32", {MVT::f32, wasm::WASM_TYPE_F32})
180         .Case("f64", {MVT::f64, wasm::WASM_TYPE_F64})
181         .Case("i8x16", {MVT::v16i8, wasm::WASM_TYPE_V128})
182         .Case("i16x8", {MVT::v8i16, wasm::WASM_TYPE_V128})
183         .Case("i32x4", {MVT::v4i32, wasm::WASM_TYPE_V128})
184         .Case("i64x2", {MVT::v2i64, wasm::WASM_TYPE_V128})
185         .Case("f32x4", {MVT::v4f32, wasm::WASM_TYPE_V128})
186         .Case("f64x2", {MVT::v2f64, wasm::WASM_TYPE_V128})
187         // arbitrarily chosen vector type to associate with "v128"
188         // FIXME: should these be EVTs to avoid this arbitrary hack? Do we want
189         // to accept more specific SIMD register types?
190         .Case("v128", {MVT::v16i8, wasm::WASM_TYPE_V128})
191         .Default({MVT::INVALID_SIMPLE_VALUE_TYPE, wasm::WASM_TYPE_NORESULT});
192   }
193 
194   void ParseSingleInteger(bool IsNegative, OperandVector &Operands) {
195     auto &Int = Lexer.getTok();
196     int64_t Val = Int.getIntVal();
197     if (IsNegative)
198       Val = -Val;
199     Operands.push_back(make_unique<WebAssemblyOperand>(
200         WebAssemblyOperand::Integer, Int.getLoc(), Int.getEndLoc(),
201         WebAssemblyOperand::IntOp{Val}));
202     Parser.Lex();
203   }
204 
205   bool ParseOperandStartingWithInteger(bool IsNegative, OperandVector &Operands,
206                                        StringRef InstName) {
207     ParseSingleInteger(IsNegative, Operands);
208     // FIXME: there is probably a cleaner way to do this.
209     auto IsLoadStore = InstName.startswith("load") ||
210                        InstName.startswith("store") ||
211                        InstName.startswith("atomic_load") ||
212                        InstName.startswith("atomic_store");
213     if (IsLoadStore) {
214       // Parse load/store operands of the form: offset align
215       auto &Offset = Lexer.getTok();
216       if (Offset.is(AsmToken::Integer)) {
217         ParseSingleInteger(false, Operands);
218       } else {
219         // Alignment not specified.
220         // FIXME: correctly derive a default from the instruction.
221         // We can't just call WebAssembly::GetDefaultP2Align since we don't have
222         // an opcode until after the assembly matcher.
223         Operands.push_back(make_unique<WebAssemblyOperand>(
224             WebAssemblyOperand::Integer, Offset.getLoc(), Offset.getEndLoc(),
225             WebAssemblyOperand::IntOp{0}));
226       }
227     }
228     return false;
229   }
230 
231   bool ParseInstruction(ParseInstructionInfo & /*Info*/, StringRef Name,
232                         SMLoc NameLoc, OperandVector &Operands) override {
233     // Note: Name does NOT point into the sourcecode, but to a local, so
234     // use NameLoc instead.
235     Name = StringRef(NameLoc.getPointer(), Name.size());
236     // WebAssembly has instructions with / in them, which AsmLexer parses
237     // as seperate tokens, so if we find such tokens immediately adjacent (no
238     // whitespace), expand the name to include them:
239     for (;;) {
240       auto &Sep = Lexer.getTok();
241       if (Sep.getLoc().getPointer() != Name.end() ||
242           Sep.getKind() != AsmToken::Slash) break;
243       // Extend name with /
244       Name = StringRef(Name.begin(), Name.size() + Sep.getString().size());
245       Parser.Lex();
246       // We must now find another identifier, or error.
247       auto &Id = Lexer.getTok();
248       if (Id.getKind() != AsmToken::Identifier ||
249           Id.getLoc().getPointer() != Name.end())
250         return Error("Incomplete instruction name: ", Id);
251       Name = StringRef(Name.begin(), Name.size() + Id.getString().size());
252       Parser.Lex();
253     }
254     // Now construct the name as first operand.
255     Operands.push_back(make_unique<WebAssemblyOperand>(
256         WebAssemblyOperand::Token, NameLoc, SMLoc::getFromPointer(Name.end()),
257         WebAssemblyOperand::TokOp{Name}));
258     auto NamePair = Name.split('.');
259     // If no '.', there is no type prefix.
260     auto BaseName = NamePair.second.empty() ? NamePair.first : NamePair.second;
261     while (Lexer.isNot(AsmToken::EndOfStatement)) {
262       auto &Tok = Lexer.getTok();
263       switch (Tok.getKind()) {
264       case AsmToken::Identifier: {
265         auto &Id = Lexer.getTok();
266         const MCExpr *Val;
267         SMLoc End;
268         if (Parser.parsePrimaryExpr(Val, End))
269           return Error("Cannot parse symbol: ", Lexer.getTok());
270         Operands.push_back(make_unique<WebAssemblyOperand>(
271             WebAssemblyOperand::Symbol, Id.getLoc(), Id.getEndLoc(),
272             WebAssemblyOperand::SymOp{Val}));
273         break;
274       }
275       case AsmToken::Minus:
276         Parser.Lex();
277         if (Lexer.isNot(AsmToken::Integer))
278           return Error("Expected integer instead got: ", Lexer.getTok());
279         if (ParseOperandStartingWithInteger(true, Operands, BaseName))
280           return true;
281         break;
282       case AsmToken::Integer:
283         if (ParseOperandStartingWithInteger(false, Operands, BaseName))
284           return true;
285         break;
286       case AsmToken::Real: {
287         double Val;
288         if (Tok.getString().getAsDouble(Val, false))
289           return Error("Cannot parse real: ", Tok);
290         Operands.push_back(make_unique<WebAssemblyOperand>(
291             WebAssemblyOperand::Float, Tok.getLoc(), Tok.getEndLoc(),
292             WebAssemblyOperand::FltOp{Val}));
293         Parser.Lex();
294         break;
295       }
296       default:
297         return Error("Unexpected token in operand: ", Tok);
298       }
299       if (Lexer.isNot(AsmToken::EndOfStatement)) {
300         if (Expect(AsmToken::Comma, ","))
301           return true;
302       }
303     }
304     Parser.Lex();
305     // Block instructions require a signature index, but these are missing in
306     // assembly, so we add a dummy one explicitly (since we have no control
307     // over signature tables here, we assume these will be regenerated when
308     // the wasm module is generated).
309     if (BaseName == "block" || BaseName == "loop" || BaseName == "try") {
310       Operands.push_back(make_unique<WebAssemblyOperand>(
311           WebAssemblyOperand::Integer, NameLoc, NameLoc,
312           WebAssemblyOperand::IntOp{-1}));
313     }
314     return false;
315   }
316 
317   void onLabelParsed(MCSymbol *Symbol) override {
318     LastSymbol = cast<MCSymbolWasm>(Symbol);
319   }
320 
321   bool ParseDirective(AsmToken DirectiveID) override {
322     // This function has a really weird return value behavior that is different
323     // from all the other parsing functions:
324     // - return true && no tokens consumed -> don't know this directive / let
325     //   the generic parser handle it.
326     // - return true && tokens consumed -> a parsing error occurred.
327     // - return false -> processed this directive successfully.
328     assert(DirectiveID.getKind() == AsmToken::Identifier);
329     auto &Out = getStreamer();
330     auto &TOut =
331         reinterpret_cast<WebAssemblyTargetStreamer &>(*Out.getTargetStreamer());
332     // TODO: any time we return an error, at least one token must have been
333     // consumed, otherwise this will not signal an error to the caller.
334     if (DirectiveID.getString() == ".type") {
335       // This could be the start of a function, check if followed by
336       // "label,@function"
337       if (!Lexer.is(AsmToken::Identifier))
338         return Error("Expected label after .type directive, got: ",
339                      Lexer.getTok());
340       auto WasmSym = cast<MCSymbolWasm>(
341                        TOut.getStreamer().getContext().getOrCreateSymbol(
342                          Lexer.getTok().getString()));
343       Parser.Lex();
344       if (!(IsNext(AsmToken::Comma) && IsNext(AsmToken::At) &&
345             Lexer.is(AsmToken::Identifier)))
346         return Error("Expected label,@type declaration, got: ", Lexer.getTok());
347       auto TypeName = Lexer.getTok().getString();
348       if (TypeName == "function")
349         WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
350       else if (TypeName == "global")
351         WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
352       else
353         return Error("Unknown WASM symbol type: ", Lexer.getTok());
354       Parser.Lex();
355       return Expect(AsmToken::EndOfStatement, "EOL");
356     } else if (DirectiveID.getString() == ".size") {
357       if (!Lexer.is(AsmToken::Identifier))
358         return Error("Expected label after .size directive, got: ",
359                      Lexer.getTok());
360       auto WasmSym = cast<MCSymbolWasm>(
361                        TOut.getStreamer().getContext().getOrCreateSymbol(
362                          Lexer.getTok().getString()));
363       Parser.Lex();
364       if (!IsNext(AsmToken::Comma))
365         return Error("Expected `,`, got: ", Lexer.getTok());
366       const MCExpr *Exp;
367       if (Parser.parseExpression(Exp))
368         return Error("Cannot parse .size expression: ", Lexer.getTok());
369       WasmSym->setSize(Exp);
370       return Expect(AsmToken::EndOfStatement, "EOL");
371     } else if (DirectiveID.getString() == ".globaltype") {
372       if (!Lexer.is(AsmToken::Identifier))
373         return Error("Expected symbol name after .globaltype directive, got: ",
374                      Lexer.getTok());
375       auto Name = Lexer.getTok().getString();
376       Parser.Lex();
377       if (!IsNext(AsmToken::Comma))
378         return Error("Expected `,`, got: ", Lexer.getTok());
379       if (!Lexer.is(AsmToken::Identifier))
380         return Error("Expected type in .globaltype directive, got: ",
381                      Lexer.getTok());
382       auto Type = ParseRegType(Lexer.getTok().getString()).second;
383       if (Type == wasm::WASM_TYPE_NORESULT)
384         return Error("Unknown type in .globaltype directive: ",
385                      Lexer.getTok());
386       Parser.Lex();
387       // Now set this symbol with the correct type.
388       auto WasmSym = cast<MCSymbolWasm>(
389                        TOut.getStreamer().getContext().getOrCreateSymbol(Name));
390       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
391       WasmSym->setGlobalType(wasm::WasmGlobalType{uint8_t(Type), true});
392       // And emit the directive again.
393       TOut.emitGlobalType(WasmSym);
394       return Expect(AsmToken::EndOfStatement, "EOL");
395     } else if (DirectiveID.getString() == ".param" ||
396                DirectiveID.getString() == ".local") {
397       // Track the number of locals, needed for correct virtual register
398       // assignment elsewhere.
399       // Also output a directive to the streamer.
400       std::vector<MVT> Params;
401       std::vector<MVT> Locals;
402       while (Lexer.is(AsmToken::Identifier)) {
403         auto RegType = ParseRegType(Lexer.getTok().getString()).first;
404         if (RegType == MVT::INVALID_SIMPLE_VALUE_TYPE)
405           return true;
406         if (DirectiveID.getString() == ".param") {
407           Params.push_back(RegType);
408         } else {
409           Locals.push_back(RegType);
410         }
411         Parser.Lex();
412         if (!IsNext(AsmToken::Comma))
413           break;
414       }
415       assert(LastSymbol);
416       // TODO: LastSymbol isn't even used by emitParam, so could be removed.
417       TOut.emitParam(LastSymbol, Params);
418       TOut.emitLocal(Locals);
419       return Expect(AsmToken::EndOfStatement, "EOL");
420     } else {
421       // TODO: remove.
422       while (Lexer.isNot(AsmToken::EndOfStatement))
423         Parser.Lex();
424       return Expect(AsmToken::EndOfStatement, "EOL");
425     }
426     // TODO: current ELF directive parsing is broken, fix this is a followup.
427     //return true;  // We didn't process this directive.
428     return false;
429   }
430 
431   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned & /*Opcode*/,
432                                OperandVector &Operands, MCStreamer &Out,
433                                uint64_t &ErrorInfo,
434                                bool MatchingInlineAsm) override {
435     MCInst Inst;
436     unsigned MatchResult =
437         MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
438     switch (MatchResult) {
439     case Match_Success: {
440       Out.EmitInstruction(Inst, getSTI());
441       return false;
442     }
443     case Match_MissingFeature:
444       return Parser.Error(
445           IDLoc, "instruction requires a WASM feature not currently enabled");
446     case Match_MnemonicFail:
447       return Parser.Error(IDLoc, "invalid instruction");
448     case Match_NearMisses:
449       return Parser.Error(IDLoc, "ambiguous instruction");
450     case Match_InvalidTiedOperand:
451     case Match_InvalidOperand: {
452       SMLoc ErrorLoc = IDLoc;
453       if (ErrorInfo != ~0ULL) {
454         if (ErrorInfo >= Operands.size())
455           return Parser.Error(IDLoc, "too few operands for instruction");
456         ErrorLoc = Operands[ErrorInfo]->getStartLoc();
457         if (ErrorLoc == SMLoc())
458           ErrorLoc = IDLoc;
459       }
460       return Parser.Error(ErrorLoc, "invalid operand for instruction");
461     }
462     }
463     llvm_unreachable("Implement any new match types added!");
464   }
465 };
466 } // end anonymous namespace
467 
468 // Force static initialization.
469 extern "C" void LLVMInitializeWebAssemblyAsmParser() {
470   RegisterMCAsmParser<WebAssemblyAsmParser> X(getTheWebAssemblyTarget32());
471   RegisterMCAsmParser<WebAssemblyAsmParser> Y(getTheWebAssemblyTarget64());
472 }
473 
474 #define GET_REGISTER_MATCHER
475 #define GET_MATCHER_IMPLEMENTATION
476 #include "WebAssemblyGenAsmMatcher.inc"
477