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 
136 public:
137   WebAssemblyAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
138                        const MCInstrInfo &MII, const MCTargetOptions &Options)
139       : MCTargetAsmParser(Options, STI, MII), Parser(Parser),
140         Lexer(Parser.getLexer()) {
141     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
142   }
143 
144 #define GET_ASSEMBLER_HEADER
145 #include "WebAssemblyGenAsmMatcher.inc"
146 
147   // TODO: This is required to be implemented, but appears unused.
148   bool ParseRegister(unsigned & /*RegNo*/, SMLoc & /*StartLoc*/,
149                      SMLoc & /*EndLoc*/) override {
150     llvm_unreachable("ParseRegister is not implemented.");
151   }
152 
153   bool Error(const StringRef &msg, const AsmToken &tok) {
154     return Parser.Error(tok.getLoc(), msg + tok.getString());
155   }
156 
157   bool IsNext(AsmToken::TokenKind Kind) {
158     auto ok = Lexer.is(Kind);
159     if (ok)
160       Parser.Lex();
161     return ok;
162   }
163 
164   bool Expect(AsmToken::TokenKind Kind, const char *KindName) {
165     if (!IsNext(Kind))
166       return Error(std::string("Expected ") + KindName + ", instead got: ",
167                    Lexer.getTok());
168     return false;
169   }
170 
171 
172   std::pair<MVT::SimpleValueType, unsigned>
173   ParseRegType(const StringRef &RegType) {
174     // Derive type from .param .local decls, or the instruction itself.
175     return StringSwitch<std::pair<MVT::SimpleValueType, unsigned>>(RegType)
176         .Case("i32", {MVT::i32, wasm::WASM_TYPE_I32})
177         .Case("i64", {MVT::i64, wasm::WASM_TYPE_I64})
178         .Case("f32", {MVT::f32, wasm::WASM_TYPE_F32})
179         .Case("f64", {MVT::f64, wasm::WASM_TYPE_F64})
180         .Case("i8x16", {MVT::v16i8, wasm::WASM_TYPE_V128})
181         .Case("i16x8", {MVT::v8i16, wasm::WASM_TYPE_V128})
182         .Case("i32x4", {MVT::v4i32, wasm::WASM_TYPE_V128})
183         .Case("i64x2", {MVT::v2i64, wasm::WASM_TYPE_V128})
184         .Case("f32x4", {MVT::v4f32, wasm::WASM_TYPE_V128})
185         .Case("f64x2", {MVT::v2f64, wasm::WASM_TYPE_V128})
186         // arbitrarily chosen vector type to associate with "v128"
187         // FIXME: should these be EVTs to avoid this arbitrary hack? Do we want
188         // to accept more specific SIMD register types?
189         .Case("v128", {MVT::v16i8, wasm::WASM_TYPE_V128})
190         .Default({MVT::INVALID_SIMPLE_VALUE_TYPE, wasm::WASM_TYPE_NORESULT});
191   }
192 
193   bool ParseRegTypeList(std::vector<MVT> &Types) {
194     while (Lexer.is(AsmToken::Identifier)) {
195       auto RegType = ParseRegType(Lexer.getTok().getString()).first;
196       if (RegType == MVT::INVALID_SIMPLE_VALUE_TYPE)
197         return true;
198       Types.push_back(RegType);
199       Parser.Lex();
200       if (!IsNext(AsmToken::Comma))
201         break;
202     }
203     return Expect(AsmToken::EndOfStatement, "EOL");
204   }
205 
206   void ParseSingleInteger(bool IsNegative, OperandVector &Operands) {
207     auto &Int = Lexer.getTok();
208     int64_t Val = Int.getIntVal();
209     if (IsNegative)
210       Val = -Val;
211     Operands.push_back(make_unique<WebAssemblyOperand>(
212         WebAssemblyOperand::Integer, Int.getLoc(), Int.getEndLoc(),
213         WebAssemblyOperand::IntOp{Val}));
214     Parser.Lex();
215   }
216 
217   bool ParseOperandStartingWithInteger(bool IsNegative, OperandVector &Operands,
218                                        StringRef InstName) {
219     ParseSingleInteger(IsNegative, Operands);
220     // FIXME: there is probably a cleaner way to do this.
221     auto IsLoadStore = InstName.startswith("load") ||
222                        InstName.startswith("store") ||
223                        InstName.startswith("atomic_load") ||
224                        InstName.startswith("atomic_store");
225     if (IsLoadStore) {
226       // Parse load/store operands of the form: offset align
227       auto &Offset = Lexer.getTok();
228       if (Offset.is(AsmToken::Integer)) {
229         ParseSingleInteger(false, Operands);
230       } else {
231         // Alignment not specified.
232         // FIXME: correctly derive a default from the instruction.
233         // We can't just call WebAssembly::GetDefaultP2Align since we don't have
234         // an opcode until after the assembly matcher.
235         Operands.push_back(make_unique<WebAssemblyOperand>(
236             WebAssemblyOperand::Integer, Offset.getLoc(), Offset.getEndLoc(),
237             WebAssemblyOperand::IntOp{0}));
238       }
239     }
240     return false;
241   }
242 
243   bool ParseInstruction(ParseInstructionInfo & /*Info*/, StringRef Name,
244                         SMLoc NameLoc, OperandVector &Operands) override {
245     // Note: Name does NOT point into the sourcecode, but to a local, so
246     // use NameLoc instead.
247     Name = StringRef(NameLoc.getPointer(), Name.size());
248     // WebAssembly has instructions with / in them, which AsmLexer parses
249     // as seperate tokens, so if we find such tokens immediately adjacent (no
250     // whitespace), expand the name to include them:
251     for (;;) {
252       auto &Sep = Lexer.getTok();
253       if (Sep.getLoc().getPointer() != Name.end() ||
254           Sep.getKind() != AsmToken::Slash) break;
255       // Extend name with /
256       Name = StringRef(Name.begin(), Name.size() + Sep.getString().size());
257       Parser.Lex();
258       // We must now find another identifier, or error.
259       auto &Id = Lexer.getTok();
260       if (Id.getKind() != AsmToken::Identifier ||
261           Id.getLoc().getPointer() != Name.end())
262         return Error("Incomplete instruction name: ", Id);
263       Name = StringRef(Name.begin(), Name.size() + Id.getString().size());
264       Parser.Lex();
265     }
266     // Now construct the name as first operand.
267     Operands.push_back(make_unique<WebAssemblyOperand>(
268         WebAssemblyOperand::Token, NameLoc, SMLoc::getFromPointer(Name.end()),
269         WebAssemblyOperand::TokOp{Name}));
270     auto NamePair = Name.split('.');
271     // If no '.', there is no type prefix.
272     auto BaseName = NamePair.second.empty() ? NamePair.first : NamePair.second;
273     while (Lexer.isNot(AsmToken::EndOfStatement)) {
274       auto &Tok = Lexer.getTok();
275       switch (Tok.getKind()) {
276       case AsmToken::Identifier: {
277         auto &Id = Lexer.getTok();
278         const MCExpr *Val;
279         SMLoc End;
280         if (Parser.parsePrimaryExpr(Val, End))
281           return Error("Cannot parse symbol: ", Lexer.getTok());
282         Operands.push_back(make_unique<WebAssemblyOperand>(
283             WebAssemblyOperand::Symbol, Id.getLoc(), Id.getEndLoc(),
284             WebAssemblyOperand::SymOp{Val}));
285         break;
286       }
287       case AsmToken::Minus:
288         Parser.Lex();
289         if (Lexer.isNot(AsmToken::Integer))
290           return Error("Expected integer instead got: ", Lexer.getTok());
291         if (ParseOperandStartingWithInteger(true, Operands, BaseName))
292           return true;
293         break;
294       case AsmToken::Integer:
295         if (ParseOperandStartingWithInteger(false, Operands, BaseName))
296           return true;
297         break;
298       case AsmToken::Real: {
299         double Val;
300         if (Tok.getString().getAsDouble(Val, false))
301           return Error("Cannot parse real: ", Tok);
302         Operands.push_back(make_unique<WebAssemblyOperand>(
303             WebAssemblyOperand::Float, Tok.getLoc(), Tok.getEndLoc(),
304             WebAssemblyOperand::FltOp{Val}));
305         Parser.Lex();
306         break;
307       }
308       default:
309         return Error("Unexpected token in operand: ", Tok);
310       }
311       if (Lexer.isNot(AsmToken::EndOfStatement)) {
312         if (Expect(AsmToken::Comma, ","))
313           return true;
314       }
315     }
316     Parser.Lex();
317     // Block instructions require a signature index, but these are missing in
318     // assembly, so we add a dummy one explicitly (since we have no control
319     // over signature tables here, we assume these will be regenerated when
320     // the wasm module is generated).
321     if (BaseName == "block" || BaseName == "loop" || BaseName == "try") {
322       Operands.push_back(make_unique<WebAssemblyOperand>(
323           WebAssemblyOperand::Integer, NameLoc, NameLoc,
324           WebAssemblyOperand::IntOp{-1}));
325     }
326     return false;
327   }
328 
329   // This function processes wasm-specific directives streamed to
330   // WebAssemblyTargetStreamer, all others go to the generic parser
331   // (see WasmAsmParser).
332   bool ParseDirective(AsmToken DirectiveID) override {
333     // This function has a really weird return value behavior that is different
334     // from all the other parsing functions:
335     // - return true && no tokens consumed -> don't know this directive / let
336     //   the generic parser handle it.
337     // - return true && tokens consumed -> a parsing error occurred.
338     // - return false -> processed this directive successfully.
339     assert(DirectiveID.getKind() == AsmToken::Identifier);
340     auto &Out = getStreamer();
341     auto &TOut =
342         reinterpret_cast<WebAssemblyTargetStreamer &>(*Out.getTargetStreamer());
343     // TODO: any time we return an error, at least one token must have been
344     // consumed, otherwise this will not signal an error to the caller.
345     if (DirectiveID.getString() == ".globaltype") {
346       if (!Lexer.is(AsmToken::Identifier))
347         return Error("Expected symbol name after .globaltype directive, got: ",
348                      Lexer.getTok());
349       auto Name = Lexer.getTok().getString();
350       Parser.Lex();
351       if (!IsNext(AsmToken::Comma))
352         return Error("Expected `,`, got: ", Lexer.getTok());
353       if (!Lexer.is(AsmToken::Identifier))
354         return Error("Expected type in .globaltype directive, got: ",
355                      Lexer.getTok());
356       auto Type = ParseRegType(Lexer.getTok().getString()).second;
357       if (Type == wasm::WASM_TYPE_NORESULT)
358         return Error("Unknown type in .globaltype directive: ",
359                      Lexer.getTok());
360       Parser.Lex();
361       // Now set this symbol with the correct type.
362       auto WasmSym = cast<MCSymbolWasm>(
363                        TOut.getStreamer().getContext().getOrCreateSymbol(Name));
364       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
365       WasmSym->setGlobalType(wasm::WasmGlobalType{uint8_t(Type), true});
366       // And emit the directive again.
367       TOut.emitGlobalType(WasmSym);
368       return Expect(AsmToken::EndOfStatement, "EOL");
369     } else if (DirectiveID.getString() == ".param") {
370       std::vector<MVT> Params;
371       if (ParseRegTypeList(Params)) return true;
372       TOut.emitParam(nullptr /* unused */, Params);
373       return false;
374     } else if (DirectiveID.getString() == ".result") {
375       std::vector<MVT> Results;
376       if (ParseRegTypeList(Results)) return true;
377       TOut.emitResult(nullptr /* unused */, Results);
378       return false;
379     } else if (DirectiveID.getString() == ".local") {
380       std::vector<MVT> Locals;
381       if (ParseRegTypeList(Locals)) return true;
382       TOut.emitLocal(Locals);
383       return false;
384     }
385     return true;  // We didn't process this directive.
386   }
387 
388   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned & /*Opcode*/,
389                                OperandVector &Operands, MCStreamer &Out,
390                                uint64_t &ErrorInfo,
391                                bool MatchingInlineAsm) override {
392     MCInst Inst;
393     unsigned MatchResult =
394         MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
395     switch (MatchResult) {
396     case Match_Success: {
397       Out.EmitInstruction(Inst, getSTI());
398       return false;
399     }
400     case Match_MissingFeature:
401       return Parser.Error(
402           IDLoc, "instruction requires a WASM feature not currently enabled");
403     case Match_MnemonicFail:
404       return Parser.Error(IDLoc, "invalid instruction");
405     case Match_NearMisses:
406       return Parser.Error(IDLoc, "ambiguous instruction");
407     case Match_InvalidTiedOperand:
408     case Match_InvalidOperand: {
409       SMLoc ErrorLoc = IDLoc;
410       if (ErrorInfo != ~0ULL) {
411         if (ErrorInfo >= Operands.size())
412           return Parser.Error(IDLoc, "too few operands for instruction");
413         ErrorLoc = Operands[ErrorInfo]->getStartLoc();
414         if (ErrorLoc == SMLoc())
415           ErrorLoc = IDLoc;
416       }
417       return Parser.Error(ErrorLoc, "invalid operand for instruction");
418     }
419     }
420     llvm_unreachable("Implement any new match types added!");
421   }
422 };
423 } // end anonymous namespace
424 
425 // Force static initialization.
426 extern "C" void LLVMInitializeWebAssemblyAsmParser() {
427   RegisterMCAsmParser<WebAssemblyAsmParser> X(getTheWebAssemblyTarget32());
428   RegisterMCAsmParser<WebAssemblyAsmParser> Y(getTheWebAssemblyTarget64());
429 }
430 
431 #define GET_REGISTER_MATCHER
432 #define GET_MATCHER_IMPLEMENTATION
433 #include "WebAssemblyGenAsmMatcher.inc"
434