1 //===- WasmAsmParser.cpp - Wasm Assembly Parser -----------------------------===//
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
9 // Note, this is for wasm, the binary format (analogous to ELF), not wasm,
10 // the instruction set (analogous to x86), for which parsing code lives in
11 // WebAssemblyAsmParser.
13 // This file contains processing for generic directives implemented using
14 // MCTargetStreamer, the ones that depend on WebAssemblyTargetStreamer are in
15 // WebAssemblyAsmParser.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/BinaryFormat/Wasm.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCParser/MCAsmLexer.h"
22 #include "llvm/MC/MCParser/MCAsmParser.h"
23 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
24 #include "llvm/MC/MCObjectFileInfo.h"
25 #include "llvm/MC/MCSectionWasm.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSymbolWasm.h"
28 #include "llvm/Support/Casting.h"
35 class WasmAsmParser : public MCAsmParserExtension {
36 MCAsmParser *Parser = nullptr;
37 MCAsmLexer *Lexer = nullptr;
39 template<bool (WasmAsmParser::*HandlerMethod)(StringRef, SMLoc)>
40 void addDirectiveHandler(StringRef Directive) {
41 MCAsmParser::ExtensionDirectiveHandler Handler = std::make_pair(
42 this, HandleDirective<WasmAsmParser, HandlerMethod>);
44 getParser().addDirectiveHandler(Directive, Handler);
48 WasmAsmParser() { BracketExpressionsSupported = true; }
50 void Initialize(MCAsmParser &P) override {
52 Lexer = &Parser->getLexer();
53 // Call the base implementation.
54 this->MCAsmParserExtension::Initialize(*Parser);
56 addDirectiveHandler<&WasmAsmParser::parseSectionDirectiveText>(".text");
57 addDirectiveHandler<&WasmAsmParser::parseSectionDirectiveData>(".data");
58 addDirectiveHandler<&WasmAsmParser::parseSectionDirective>(".section");
59 addDirectiveHandler<&WasmAsmParser::parseDirectiveSize>(".size");
60 addDirectiveHandler<&WasmAsmParser::parseDirectiveType>(".type");
61 addDirectiveHandler<&WasmAsmParser::ParseDirectiveIdent>(".ident");
63 &WasmAsmParser::ParseDirectiveSymbolAttribute>(".weak");
65 &WasmAsmParser::ParseDirectiveSymbolAttribute>(".local");
67 &WasmAsmParser::ParseDirectiveSymbolAttribute>(".internal");
69 &WasmAsmParser::ParseDirectiveSymbolAttribute>(".hidden");
72 bool error(const StringRef &Msg, const AsmToken &Tok) {
73 return Parser->Error(Tok.getLoc(), Msg + Tok.getString());
76 bool isNext(AsmToken::TokenKind Kind) {
77 auto Ok = Lexer->is(Kind);
83 bool expect(AsmToken::TokenKind Kind, const char *KindName) {
85 return error(std::string("Expected ") + KindName + ", instead got: ",
90 bool parseSectionDirectiveText(StringRef, SMLoc) {
91 // FIXME: .text currently no-op.
95 bool parseSectionDirectiveData(StringRef, SMLoc) {
96 auto *S = getContext().getObjectFileInfo()->getDataSection();
97 getStreamer().switchSection(S);
101 uint32_t parseSectionFlags(StringRef FlagStr, bool &Passive, bool &Group) {
103 for (char C : FlagStr) {
112 flags |= wasm::WASM_SEG_FLAG_TLS;
115 flags |= wasm::WASM_SEG_FLAG_STRINGS;
124 bool parseGroup(StringRef &GroupName) {
125 if (Lexer->isNot(AsmToken::Comma))
126 return TokError("expected group name");
128 if (Lexer->is(AsmToken::Integer)) {
129 GroupName = getTok().getString();
131 } else if (Parser->parseIdentifier(GroupName)) {
132 return TokError("invalid group name");
134 if (Lexer->is(AsmToken::Comma)) {
137 if (Parser->parseIdentifier(Linkage))
138 return TokError("invalid linkage");
139 if (Linkage != "comdat")
140 return TokError("Linkage must be 'comdat'");
145 bool parseSectionDirective(StringRef, SMLoc loc) {
147 if (Parser->parseIdentifier(Name))
148 return TokError("expected identifier in directive");
150 if (expect(AsmToken::Comma, ","))
153 if (Lexer->isNot(AsmToken::String))
154 return error("expected string in directive, instead got: ", Lexer->getTok());
156 auto Kind = StringSwitch<std::optional<SectionKind>>(Name)
157 .StartsWith(".data", SectionKind::getData())
158 .StartsWith(".tdata", SectionKind::getThreadData())
159 .StartsWith(".tbss", SectionKind::getThreadBSS())
160 .StartsWith(".rodata", SectionKind::getReadOnly())
161 .StartsWith(".text", SectionKind::getText())
162 .StartsWith(".custom_section", SectionKind::getMetadata())
163 .StartsWith(".bss", SectionKind::getBSS())
164 // See use of .init_array in WasmObjectWriter and
165 // TargetLoweringObjectFileWasm
166 .StartsWith(".init_array", SectionKind::getData())
167 .StartsWith(".debug_", SectionKind::getMetadata())
168 .Default(SectionKind::getData());
170 // Update section flags if present in this .section directive
171 bool Passive = false;
174 parseSectionFlags(getTok().getStringContents(), Passive, Group);
176 return TokError("unknown flag");
180 if (expect(AsmToken::Comma, ",") || expect(AsmToken::At, "@"))
184 if (Group && parseGroup(GroupName))
187 if (expect(AsmToken::EndOfStatement, "eol"))
190 // TODO: Parse UniqueID
191 MCSectionWasm *WS = getContext().getWasmSection(
192 Name, *Kind, Flags, GroupName, MCContext::GenericSectionID);
194 if (WS->getSegmentFlags() != Flags)
195 Parser->Error(loc, "changed section flags for " + Name +
197 utohexstr(WS->getSegmentFlags()));
200 if (!WS->isWasmData())
201 return Parser->Error(loc, "Only data sections can be passive");
205 getStreamer().switchSection(WS);
209 // TODO: This function is almost the same as ELFAsmParser::ParseDirectiveSize
210 // so maybe could be shared somehow.
211 bool parseDirectiveSize(StringRef, SMLoc Loc) {
213 if (Parser->parseIdentifier(Name))
214 return TokError("expected identifier in directive");
215 auto Sym = getContext().getOrCreateSymbol(Name);
216 if (expect(AsmToken::Comma, ","))
219 if (Parser->parseExpression(Expr))
221 if (expect(AsmToken::EndOfStatement, "eol"))
223 auto WasmSym = cast<MCSymbolWasm>(Sym);
224 if (WasmSym->isFunction()) {
225 // Ignore .size directives for function symbols. They get their size
226 // set automatically based on their content.
227 Warning(Loc, ".size directive ignored for function symbols");
229 getStreamer().emitELFSize(Sym, Expr);
234 bool parseDirectiveType(StringRef, SMLoc) {
235 // This could be the start of a function, check if followed by
237 if (!Lexer->is(AsmToken::Identifier))
238 return error("Expected label after .type directive, got: ",
240 auto WasmSym = cast<MCSymbolWasm>(
241 getStreamer().getContext().getOrCreateSymbol(
242 Lexer->getTok().getString()));
244 if (!(isNext(AsmToken::Comma) && isNext(AsmToken::At) &&
245 Lexer->is(AsmToken::Identifier)))
246 return error("Expected label,@type declaration, got: ", Lexer->getTok());
247 auto TypeName = Lexer->getTok().getString();
248 if (TypeName == "function") {
249 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
251 cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
252 if (Current->getGroup())
253 WasmSym->setComdat(true);
254 } else if (TypeName == "global")
255 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
256 else if (TypeName == "object")
257 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_DATA);
259 return error("Unknown WASM symbol type: ", Lexer->getTok());
261 return expect(AsmToken::EndOfStatement, "EOL");
264 // FIXME: Shared with ELF.
265 /// ParseDirectiveIdent
266 /// ::= .ident string
267 bool ParseDirectiveIdent(StringRef, SMLoc) {
268 if (getLexer().isNot(AsmToken::String))
269 return TokError("unexpected token in '.ident' directive");
270 StringRef Data = getTok().getIdentifier();
272 if (getLexer().isNot(AsmToken::EndOfStatement))
273 return TokError("unexpected token in '.ident' directive");
275 getStreamer().emitIdent(Data);
279 // FIXME: Shared with ELF.
280 /// ParseDirectiveSymbolAttribute
281 /// ::= { ".local", ".weak", ... } [ identifier ( , identifier )* ]
282 bool ParseDirectiveSymbolAttribute(StringRef Directive, SMLoc) {
283 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Directive)
284 .Case(".weak", MCSA_Weak)
285 .Case(".local", MCSA_Local)
286 .Case(".hidden", MCSA_Hidden)
287 .Case(".internal", MCSA_Internal)
288 .Case(".protected", MCSA_Protected)
289 .Default(MCSA_Invalid);
290 assert(Attr != MCSA_Invalid && "unexpected symbol attribute directive!");
291 if (getLexer().isNot(AsmToken::EndOfStatement)) {
294 if (getParser().parseIdentifier(Name))
295 return TokError("expected identifier in directive");
296 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
297 getStreamer().emitSymbolAttribute(Sym, Attr);
298 if (getLexer().is(AsmToken::EndOfStatement))
300 if (getLexer().isNot(AsmToken::Comma))
301 return TokError("unexpected token in directive");
310 } // end anonymous namespace
314 MCAsmParserExtension *createWasmAsmParser() {
315 return new WasmAsmParser;
318 } // end namespace llvm