LLVM 22.0.0git
WasmAsmParser.cpp
Go to the documentation of this file.
1//===- WasmAsmParser.cpp - Wasm Assembly Parser -----------------------------===//
2//
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
6//
7// --
8//
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.
12//
13// This file contains processing for generic directives implemented using
14// MCTargetStreamer, the ones that depend on WebAssemblyTargetStreamer are in
15// WebAssemblyAsmParser.
16//
17//===----------------------------------------------------------------------===//
18
21#include "llvm/MC/MCContext.h"
27#include "llvm/MC/MCStreamer.h"
29#include <optional>
30
31using namespace llvm;
32
33namespace {
34
35class WasmAsmParser : public MCAsmParserExtension {
36 MCAsmParser *Parser = nullptr;
37 AsmLexer *Lexer = nullptr;
38
39 template<bool (WasmAsmParser::*HandlerMethod)(StringRef, SMLoc)>
40 void addDirectiveHandler(StringRef Directive) {
41 MCAsmParser::ExtensionDirectiveHandler Handler = std::make_pair(
42 this, HandleDirective<WasmAsmParser, HandlerMethod>);
43
44 getParser().addDirectiveHandler(Directive, Handler);
45 }
46
47public:
48 WasmAsmParser() { BracketExpressionsSupported = true; }
49
50 void Initialize(MCAsmParser &P) override {
51 Parser = &P;
52 Lexer = &Parser->getLexer();
53 // Call the base implementation.
55
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");
62 addDirectiveHandler<
63 &WasmAsmParser::ParseDirectiveSymbolAttribute>(".weak");
64 addDirectiveHandler<
65 &WasmAsmParser::ParseDirectiveSymbolAttribute>(".local");
66 addDirectiveHandler<
67 &WasmAsmParser::ParseDirectiveSymbolAttribute>(".internal");
68 addDirectiveHandler<
69 &WasmAsmParser::ParseDirectiveSymbolAttribute>(".hidden");
70 }
71
72 bool error(const StringRef &Msg, const AsmToken &Tok) {
73 return Parser->Error(Tok.getLoc(), Msg + Tok.getString());
74 }
75
76 bool isNext(AsmToken::TokenKind Kind) {
77 auto Ok = Lexer->is(Kind);
78 if (Ok)
79 Lex();
80 return Ok;
81 }
82
83 bool expect(AsmToken::TokenKind Kind, const char *KindName) {
84 if (!isNext(Kind))
85 return error(std::string("Expected ") + KindName + ", instead got: ",
86 Lexer->getTok());
87 return false;
88 }
89
90 bool parseSectionDirectiveText(StringRef, SMLoc) {
91 // FIXME: .text currently no-op.
92 return false;
93 }
94
95 bool parseSectionDirectiveData(StringRef, SMLoc) {
96 auto *S = getContext().getObjectFileInfo()->getDataSection();
97 getStreamer().switchSection(S);
98 return false;
99 }
100
101 uint32_t parseSectionFlags(StringRef FlagStr, bool &Passive, bool &Group) {
102 uint32_t flags = 0;
103 for (char C : FlagStr) {
104 switch (C) {
105 case 'p':
106 Passive = true;
107 break;
108 case 'G':
109 Group = true;
110 break;
111 case 'T':
113 break;
114 case 'S':
116 break;
117 case 'R':
119 break;
120 default:
121 return -1U;
122 }
123 }
124 return flags;
125 }
126
127 bool parseGroup(StringRef &GroupName) {
128 if (Lexer->isNot(AsmToken::Comma))
129 return TokError("expected group name");
130 Lex();
131 if (Lexer->is(AsmToken::Integer)) {
132 GroupName = getTok().getString();
133 Lex();
134 } else if (Parser->parseIdentifier(GroupName)) {
135 return TokError("invalid group name");
136 }
137 if (Lexer->is(AsmToken::Comma)) {
138 Lex();
139 StringRef Linkage;
140 if (Parser->parseIdentifier(Linkage))
141 return TokError("invalid linkage");
142 if (Linkage != "comdat")
143 return TokError("Linkage must be 'comdat'");
144 }
145 return false;
146 }
147
148 bool parseSectionDirective(StringRef, SMLoc loc) {
149 StringRef Name;
150 if (Parser->parseIdentifier(Name))
151 return TokError("expected identifier in directive");
152
153 if (expect(AsmToken::Comma, ","))
154 return true;
155
156 if (Lexer->isNot(AsmToken::String))
157 return error("expected string in directive, instead got: ", Lexer->getTok());
158
159 auto Kind = StringSwitch<std::optional<SectionKind>>(Name)
160 .StartsWith(".data", SectionKind::getData())
161 .StartsWith(".tdata", SectionKind::getThreadData())
162 .StartsWith(".tbss", SectionKind::getThreadBSS())
163 .StartsWith(".rodata", SectionKind::getReadOnly())
164 .StartsWith(".text", SectionKind::getText())
165 .StartsWith(".custom_section", SectionKind::getMetadata())
166 .StartsWith(".bss", SectionKind::getBSS())
167 // See use of .init_array in WasmObjectWriter and
168 // TargetLoweringObjectFileWasm
169 .StartsWith(".init_array", SectionKind::getData())
170 .StartsWith(".debug_", SectionKind::getMetadata())
171 .Default(SectionKind::getData());
172
173 // Update section flags if present in this .section directive
174 bool Passive = false;
175 bool Group = false;
176 uint32_t Flags =
177 parseSectionFlags(getTok().getStringContents(), Passive, Group);
178 if (Flags == -1U)
179 return TokError("unknown flag");
180
181 Lex();
182
183 if (expect(AsmToken::Comma, ",") || expect(AsmToken::At, "@"))
184 return true;
185
186 StringRef GroupName;
187 if (Group && parseGroup(GroupName))
188 return true;
189
190 if (expect(AsmToken::EndOfStatement, "eol"))
191 return true;
192
193 // TODO: Parse UniqueID
194 MCSectionWasm *WS = getContext().getWasmSection(
195 Name, *Kind, Flags, GroupName, MCSection::NonUniqueID);
196
197 if (WS->getSegmentFlags() != Flags)
198 Parser->Error(loc, "changed section flags for " + Name +
199 ", expected: 0x" +
201
202 if (Passive) {
203 if (!WS->isWasmData())
204 return Parser->Error(loc, "Only data sections can be passive");
205 WS->setPassive();
206 }
207
208 getStreamer().switchSection(WS);
209 return false;
210 }
211
212 // TODO: This function is almost the same as ELFAsmParser::ParseDirectiveSize
213 // so maybe could be shared somehow.
214 bool parseDirectiveSize(StringRef, SMLoc Loc) {
215 StringRef Name;
216 if (Parser->parseIdentifier(Name))
217 return TokError("expected identifier in directive");
218 auto Sym = getContext().getOrCreateSymbol(Name);
219 if (expect(AsmToken::Comma, ","))
220 return true;
221 const MCExpr *Expr;
222 if (Parser->parseExpression(Expr))
223 return true;
224 if (expect(AsmToken::EndOfStatement, "eol"))
225 return true;
226 auto WasmSym = static_cast<const MCSymbolWasm *>(Sym);
227 if (WasmSym->isFunction()) {
228 // Ignore .size directives for function symbols. They get their size
229 // set automatically based on their content.
230 Warning(Loc, ".size directive ignored for function symbols");
231 } else {
232 getStreamer().emitELFSize(Sym, Expr);
233 }
234 return false;
235 }
236
237 bool parseDirectiveType(StringRef, SMLoc) {
238 // This could be the start of a function, check if followed by
239 // "label,@function"
240 if (!Lexer->is(AsmToken::Identifier))
241 return error("Expected label after .type directive, got: ",
242 Lexer->getTok());
243 auto *WasmSym = static_cast<MCSymbolWasm *>(
244 getStreamer().getContext().getOrCreateSymbol(
245 Lexer->getTok().getString()));
246 Lex();
247 if (!(isNext(AsmToken::Comma) && isNext(AsmToken::At) &&
248 Lexer->is(AsmToken::Identifier)))
249 return error("Expected label,@type declaration, got: ", Lexer->getTok());
250 auto TypeName = Lexer->getTok().getString();
251 if (TypeName == "function") {
252 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
253 auto *Current =
254 static_cast<MCSectionWasm *>(getStreamer().getCurrentSectionOnly());
255 if (Current->getGroup())
256 WasmSym->setComdat(true);
257 } else if (TypeName == "global")
258 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
259 else if (TypeName == "object")
260 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_DATA);
261 else
262 return error("Unknown WASM symbol type: ", Lexer->getTok());
263 Lex();
264 return expect(AsmToken::EndOfStatement, "EOL");
265 }
266
267 // FIXME: Shared with ELF.
268 /// ParseDirectiveIdent
269 /// ::= .ident string
270 bool ParseDirectiveIdent(StringRef, SMLoc) {
271 if (getLexer().isNot(AsmToken::String))
272 return TokError("unexpected token in '.ident' directive");
273 StringRef Data = getTok().getIdentifier();
274 Lex();
275 if (getLexer().isNot(AsmToken::EndOfStatement))
276 return TokError("unexpected token in '.ident' directive");
277 Lex();
278 getStreamer().emitIdent(Data);
279 return false;
280 }
281
282 // FIXME: Shared with ELF.
283 /// ParseDirectiveSymbolAttribute
284 /// ::= { ".local", ".weak", ... } [ identifier ( , identifier )* ]
285 bool ParseDirectiveSymbolAttribute(StringRef Directive, SMLoc) {
286 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Directive)
287 .Case(".weak", MCSA_Weak)
288 .Case(".local", MCSA_Local)
289 .Case(".hidden", MCSA_Hidden)
290 .Case(".internal", MCSA_Internal)
291 .Case(".protected", MCSA_Protected)
292 .Default(MCSA_Invalid);
293 assert(Attr != MCSA_Invalid && "unexpected symbol attribute directive!");
294 if (getLexer().isNot(AsmToken::EndOfStatement)) {
295 while (true) {
296 StringRef Name;
297 if (getParser().parseIdentifier(Name))
298 return TokError("expected identifier in directive");
299 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
300 getStreamer().emitSymbolAttribute(Sym, Attr);
301 if (getLexer().is(AsmToken::EndOfStatement))
302 break;
303 if (getLexer().isNot(AsmToken::Comma))
304 return TokError("unexpected token in directive");
305 Lex();
306 }
307 }
308 Lex();
309 return false;
310 }
311};
312
313} // end anonymous namespace
314
315namespace llvm {
316
318 return new WasmAsmParser;
319}
320
321} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isNot(const MachineRegisterInfo &MRI, const MachineInstr &MI)
DXIL Finalize Linkage
static unsigned parseSectionFlags(const Triple &TT, StringRef flagsStr, bool *UseLastGroup)
#define P(N)
This file contains some functions that are useful when dealing with strings.
#define error(X)
LLVM_ABI SMLoc getLoc() const
Definition AsmLexer.cpp:32
StringRef getString() const
Get the string for the current token, this includes all characters (for example, the quotes on string...
Definition MCAsmMacro.h:103
Generic interface for extending the MCAsmParser, which is implemented by target and object file assem...
virtual void Initialize(MCAsmParser &Parser)
Initialize the extension for parsing using the given Parser.
std::pair< MCAsmParserExtension *, DirectiveHandler > ExtensionDirectiveHandler
void setPassive(bool V=true)
bool isWasmData() const
unsigned getSegmentFlags() const
static constexpr unsigned NonUniqueID
Definition MCSection.h:501
static SectionKind getThreadData()
static SectionKind getMetadata()
static SectionKind getText()
static SectionKind getData()
static SectionKind getBSS()
static SectionKind getThreadBSS()
static SectionKind getReadOnly()
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
Context & getContext() const
Definition BasicBlock.h:99
@ WASM_SYMBOL_TYPE_GLOBAL
Definition Wasm.h:222
@ WASM_SYMBOL_TYPE_DATA
Definition Wasm.h:221
@ WASM_SYMBOL_TYPE_FUNCTION
Definition Wasm.h:220
@ WASM_SEG_FLAG_RETAIN
Definition Wasm.h:231
@ WASM_SEG_FLAG_TLS
Definition Wasm.h:230
@ WASM_SEG_FLAG_STRINGS
Definition Wasm.h:229
This is an optimization pass for GlobalISel generic memory operations.
std::string utohexstr(uint64_t X, bool LowerCase=false, unsigned Width=0)
MCAsmParserExtension * createWasmAsmParser()
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:189
@ MCSA_Local
.local (ELF)
@ MCSA_Protected
.protected (ELF)
@ MCSA_Internal
.internal (ELF)
@ MCSA_Weak
.weak
@ MCSA_Hidden
.hidden (ELF)
@ MCSA_Invalid
Not a valid directive.