LLVM 22.0.0git
MCAsmParser.h
Go to the documentation of this file.
1//===- llvm/MC/MCAsmParser.h - Abstract Asm Parser Interface ----*- C++ -*-===//
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#ifndef LLVM_MC_MCPARSER_MCASMPARSER_H
10#define LLVM_MC_MCPARSER_MCASMPARSER_H
11
15#include "llvm/ADT/StringRef.h"
16#include "llvm/ADT/Twine.h"
17#include "llvm/MC/MCAsmMacro.h"
18#include "llvm/MC/MCContext.h"
21#include "llvm/Support/SMLoc.h"
22#include <cstdint>
23#include <string>
24#include <utility>
25
26namespace llvm {
27
28class MCAsmInfo;
29class MCAsmParserExtension;
30class MCExpr;
31class MCInstPrinter;
32class MCInstrInfo;
33class MCStreamer;
34class MCTargetAsmParser;
35class SourceMgr;
36
38 enum IdKind {
39 IK_Invalid, // Initial state. Unexpected after a successful parsing.
40 IK_Label, // Function/Label reference.
41 IK_EnumVal, // Value of enumeration type.
42 IK_Var // Variable.
43 };
44 // Represents an Enum value
46 int64_t EnumVal;
47 };
48 // Represents a label/function reference
50 void *Decl;
51 };
52 // Represents a variable
54 void *Decl;
56 unsigned Length;
57 unsigned Size;
58 unsigned Type;
59 };
60 // An InlineAsm identifier can only be one of those
61 union {
65 };
66 bool isKind(IdKind kind) const { return Kind == kind; }
67 // Initializers
68 void setEnum(int64_t enumVal) {
69 assert(isKind(IK_Invalid) && "should be initialized only once");
70 Kind = IK_EnumVal;
71 Enum.EnumVal = enumVal;
72 }
73 void setLabel(void *decl) {
74 assert(isKind(IK_Invalid) && "should be initialized only once");
75 Kind = IK_Label;
76 Label.Decl = decl;
77 }
78 void setVar(void *decl, bool isGlobalLV, unsigned size, unsigned type) {
79 assert(isKind(IK_Invalid) && "should be initialized only once");
80 Kind = IK_Var;
81 Var.Decl = decl;
82 Var.IsGlobalLV = isGlobalLV;
83 Var.Size = size;
84 Var.Type = type;
85 Var.Length = size / type;
86 }
88
89private:
90 // Discriminate using the current kind.
91 IdKind Kind = IK_Invalid;
92};
93
94// Generic type information for an assembly object.
95// All sizes measured in bytes.
98 unsigned Size = 0;
99 unsigned ElementSize = 0;
100 unsigned Length = 0;
101};
102
105 unsigned Offset = 0;
106};
107
108/// Generic Sema callback for assembly parser.
110public:
112
115 bool IsUnevaluatedContext) = 0;
117 SMLoc Location, bool Create) = 0;
118 virtual bool LookupInlineAsmField(StringRef Base, StringRef Member,
119 unsigned &Offset) = 0;
120};
121
122/// Generic assembler parser interface, for use by target specific
123/// assembly parsers.
125public:
128 std::pair<MCAsmParserExtension*, DirectiveHandler>;
129
134 };
135
136private:
137 MCTargetAsmParser *TargetParser = nullptr;
138
139protected: // Can only create subclasses.
141
148
149 /// Flag tracking whether any errors have been encountered.
150 bool HadError = false;
151
152 bool ShowParsedOperands = false;
153
154public:
155 MCAsmParser(const MCAsmParser &) = delete;
157 virtual ~MCAsmParser();
158
160 ExtensionDirectiveHandler Handler) = 0;
161
163
164 MCContext &getContext() { return Ctx; }
165 MCStreamer &getStreamer() { return Out; }
167 AsmLexer &getLexer() { return Lexer; }
168 const AsmLexer &getLexer() const { return Lexer; }
169
170 MCTargetAsmParser &getTargetParser() const { return *TargetParser; }
171 void setTargetParser(MCTargetAsmParser &P);
172
173 virtual unsigned getAssemblerDialect() { return 0;}
174 virtual void setAssemblerDialect(unsigned i) { }
175
176 bool getShowParsedOperands() const { return ShowParsedOperands; }
177 void setShowParsedOperands(bool Value) { ShowParsedOperands = Value; }
178
179 /// Run the parser on the input source buffer.
180 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false) = 0;
181
182 virtual void setParsingMSInlineAsm(bool V) = 0;
183 virtual bool isParsingMSInlineAsm() = 0;
184
185 virtual bool discardLTOSymbol(StringRef) const { return false; }
186
187 virtual bool isParsingMasm() const { return false; }
188
189 virtual bool defineMacro(StringRef Name, StringRef Value) { return true; }
190
192 return true;
193 }
194 virtual bool lookUpField(StringRef Base, StringRef Member,
195 AsmFieldInfo &Info) const {
196 return true;
197 }
198
199 virtual bool lookUpType(StringRef Name, AsmTypeInfo &Info) const {
200 return true;
201 }
202
203 /// Parse MS-style inline assembly.
204 virtual bool parseMSInlineAsm(
205 std::string &AsmString, unsigned &NumOutputs, unsigned &NumInputs,
206 SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
207 SmallVectorImpl<std::string> &Constraints,
208 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
210
211 /// Emit a note at the location \p L, with the message \p Msg.
212 virtual void Note(SMLoc L, const Twine &Msg,
213 SMRange Range = std::nullopt) = 0;
214
215 /// Emit a warning at the location \p L, with the message \p Msg.
216 ///
217 /// \return The return value is true, if warnings are fatal.
218 virtual bool Warning(SMLoc L, const Twine &Msg,
219 SMRange Range = std::nullopt) = 0;
220
221 /// Return an error at the location \p L, with the message \p Msg. This
222 /// may be modified before being emitted.
223 ///
224 /// \return The return value is always true, as an idiomatic convenience to
225 /// clients.
226 bool Error(SMLoc L, const Twine &Msg, SMRange Range = std::nullopt);
227
228 /// Emit an error at the location \p L, with the message \p Msg.
229 ///
230 /// \return The return value is always true, as an idiomatic convenience to
231 /// clients.
232 virtual bool printError(SMLoc L, const Twine &Msg,
233 SMRange Range = std::nullopt) = 0;
234
235 bool hasPendingError() { return !PendingErrors.empty(); }
236
238 bool rv = !PendingErrors.empty();
239 for (auto &Err : PendingErrors) {
240 printError(Err.Loc, Twine(Err.Msg), Err.Range);
241 }
242 PendingErrors.clear();
243 return rv;
244 }
245
246 void clearPendingErrors() { PendingErrors.clear(); }
247
248 bool addErrorSuffix(const Twine &Suffix);
249
250 /// Get the next AsmToken in the stream, possibly handling file
251 /// inclusion first.
252 virtual const AsmToken &Lex() = 0;
253
254 /// Get the current AsmToken from the stream.
255 const AsmToken &getTok() const;
256
257 /// Report an error at the current lexer location.
258 bool TokError(const Twine &Msg, SMRange Range = std::nullopt);
259
260 bool parseTokenLoc(SMLoc &Loc);
261 bool parseToken(AsmToken::TokenKind T, const Twine &Msg = "unexpected token");
262 /// Attempt to parse and consume token, returning true on
263 /// success.
264 bool parseOptionalToken(AsmToken::TokenKind T);
265
266 bool parseComma() { return parseToken(AsmToken::Comma, "expected comma"); }
267 bool parseRParen() { return parseToken(AsmToken::RParen, "expected ')'"); }
268 bool parseEOL();
269 bool parseEOL(const Twine &ErrMsg);
270
271 bool parseMany(function_ref<bool()> parseOne, bool hasComma = true);
272
273 bool parseIntToken(int64_t &V, const Twine &ErrMsg = "expected integer");
274
275 bool check(bool P, const Twine &Msg);
276 bool check(bool P, SMLoc Loc, const Twine &Msg);
277
278 /// Parse an identifier or string (as a quoted identifier) and set \p
279 /// Res to the identifier contents.
280 virtual bool parseIdentifier(StringRef &Res) = 0;
281
282 /// Parse up to the end of statement and return the contents from the
283 /// current token until the end of the statement; the current token on exit
284 /// will be either the EndOfStatement or EOF.
286
287 /// Parse the current token as a string which may include escaped
288 /// characters and return the string contents.
289 virtual bool parseEscapedString(std::string &Data) = 0;
290
291 /// Parse an angle-bracket delimited string at the current position if one is
292 /// present, returning the string contents.
293 virtual bool parseAngleBracketString(std::string &Data) = 0;
294
295 /// Skip to the end of the current statement, for error recovery.
296 virtual void eatToEndOfStatement() = 0;
297
298 /// Parse an arbitrary expression.
299 ///
300 /// \param Res - The value of the expression. The result is undefined
301 /// on error.
302 /// \return - False on success.
303 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) = 0;
304 bool parseExpression(const MCExpr *&Res);
305
306 /// Parse a primary expression.
307 ///
308 /// \param Res - The value of the expression. The result is undefined
309 /// on error.
310 /// \return - False on success.
311 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc,
312 AsmTypeInfo *TypeInfo = nullptr) = 0;
313
314 /// Parse an arbitrary expression, assuming that an initial '(' has
315 /// already been consumed.
316 ///
317 /// \param Res - The value of the expression. The result is undefined
318 /// on error.
319 /// \return - False on success.
320 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) = 0;
321
322 /// Parse an expression which must evaluate to an absolute value.
323 ///
324 /// \param Res - The value of the absolute expression. The result is undefined
325 /// on error.
326 /// \return - False on success.
327 virtual bool parseAbsoluteExpression(int64_t &Res) = 0;
328
329 /// Ensure that we have a valid section set in the streamer. Otherwise,
330 /// report an error and switch to .text.
331 /// \return - False on success.
332 virtual bool checkForValidSection() = 0;
333
334 /// Parse a .gnu_attribute.
335 bool parseGNUAttribute(SMLoc L, int64_t &Tag, int64_t &IntegerValue);
336
337 bool parseAtSpecifier(const MCExpr *&Res, SMLoc &EndLoc);
338 const MCExpr *applySpecifier(const MCExpr *E, uint32_t Variant);
339};
340
341/// Create an MCAsmParser instance for parsing assembly similar to gas syntax
343 const MCAsmInfo &, unsigned CB = 0);
344
345/// Create an MCAsmParser instance for parsing Microsoft MASM-style assembly
347 const MCAsmInfo &, struct tm,
348 unsigned CB = 0);
349
350} // end namespace llvm
351
352#endif // LLVM_MC_MCPARSER_MCASMPARSER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
#define LLVM_ABI
Definition: Compiler.h:213
std::string Name
uint64_t Offset
Definition: ELF_riscv.cpp:478
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
StandardInstrumentations SI(Mod->getContext(), Debug, VerifyEach)
This file defines the SmallString class.
This file defines the SmallVector class.
Target independent representation for an assembler token.
Definition: MCAsmMacro.h:22
Lightweight error class with error context and mandatory checking.
Definition: Error.h:159
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:64
Generic interface for extending the MCAsmParser, which is implemented by target and object file assem...
Generic Sema callback for assembly parser.
Definition: MCAsmParser.h:109
virtual bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset)=0
virtual StringRef LookupInlineAsmLabel(StringRef Identifier, SourceMgr &SM, SMLoc Location, bool Create)=0
virtual void LookupInlineAsmIdentifier(StringRef &LineBuf, InlineAsmIdentifierInfo &Info, bool IsUnevaluatedContext)=0
Generic assembler parser interface, for use by target specific assembly parsers.
Definition: MCAsmParser.h:124
virtual void eatToEndOfStatement()=0
Skip to the end of the current statement, for error recovery.
virtual bool printError(SMLoc L, const Twine &Msg, SMRange Range=std::nullopt)=0
Emit an error at the location L, with the message Msg.
bool printPendingErrors()
Definition: MCAsmParser.h:237
virtual bool parseEscapedString(std::string &Data)=0
Parse the current token as a string which may include escaped characters and return the string conten...
virtual bool defineMacro(StringRef Name, StringRef Value)
Definition: MCAsmParser.h:189
void clearPendingErrors()
Definition: MCAsmParser.h:246
bool hasPendingError()
Definition: MCAsmParser.h:235
MCContext & getContext()
Definition: MCAsmParser.h:164
virtual void Note(SMLoc L, const Twine &Msg, SMRange Range=std::nullopt)=0
Emit a note at the location L, with the message Msg.
virtual StringRef parseStringToEndOfStatement()=0
Parse up to the end of statement and return the contents from the current token until the end of the ...
virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc)=0
Parse an arbitrary expression.
AsmLexer & getLexer()
Definition: MCAsmParser.h:167
virtual bool checkForValidSection()=0
Ensure that we have a valid section set in the streamer.
virtual bool isParsingMasm() const
Definition: MCAsmParser.h:187
virtual bool parseIdentifier(StringRef &Res)=0
Parse an identifier or string (as a quoted identifier) and set Res to the identifier contents.
MCAsmParser(const MCAsmParser &)=delete
bool getShowParsedOperands() const
Definition: MCAsmParser.h:176
virtual bool discardLTOSymbol(StringRef) const
Definition: MCAsmParser.h:185
MCAsmParser & operator=(const MCAsmParser &)=delete
SmallVector< MCPendingError, 0 > PendingErrors
Definition: MCAsmParser.h:147
virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc)=0
Parse an arbitrary expression, assuming that an initial '(' has already been consumed.
virtual bool isParsingMSInlineAsm()=0
MCStreamer & Out
Definition: MCAsmParser.h:143
std::pair< MCAsmParserExtension *, DirectiveHandler > ExtensionDirectiveHandler
Definition: MCAsmParser.h:128
virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc, AsmTypeInfo *TypeInfo=nullptr)=0
Parse a primary expression.
virtual const AsmToken & Lex()=0
Get the next AsmToken in the stream, possibly handling file inclusion first.
SourceMgr & SrcMgr
Definition: MCAsmParser.h:144
virtual unsigned getAssemblerDialect()
Definition: MCAsmParser.h:173
void setShowParsedOperands(bool Value)
Definition: MCAsmParser.h:177
bool(*)(MCAsmParserExtension *, StringRef, SMLoc) DirectiveHandler
Definition: MCAsmParser.h:126
virtual bool Warning(SMLoc L, const Twine &Msg, SMRange Range=std::nullopt)=0
Emit a warning at the location L, with the message Msg.
virtual bool Run(bool NoInitialTextSection, bool NoFinalize=false)=0
Run the parser on the input source buffer.
MCContext & Ctx
Definition: MCAsmParser.h:142
virtual void addAliasForDirective(StringRef Directive, StringRef Alias)=0
virtual bool parseAngleBracketString(std::string &Data)=0
Parse an angle-bracket delimited string at the current position if one is present,...
const MCAsmInfo & MAI
Definition: MCAsmParser.h:145
virtual ~MCAsmParser()
virtual bool lookUpType(StringRef Name, AsmTypeInfo &Info) const
Definition: MCAsmParser.h:199
SourceMgr & getSourceManager()
Definition: MCAsmParser.h:166
virtual bool lookUpField(StringRef Base, StringRef Member, AsmFieldInfo &Info) const
Definition: MCAsmParser.h:194
virtual bool parseAbsoluteExpression(int64_t &Res)=0
Parse an expression which must evaluate to an absolute value.
virtual bool lookUpField(StringRef Name, AsmFieldInfo &Info) const
Definition: MCAsmParser.h:191
const AsmLexer & getLexer() const
Definition: MCAsmParser.h:168
MCStreamer & getStreamer()
Definition: MCAsmParser.h:165
virtual void setAssemblerDialect(unsigned i)
Definition: MCAsmParser.h:174
virtual void setParsingMSInlineAsm(bool V)=0
virtual bool parseMSInlineAsm(std::string &AsmString, unsigned &NumOutputs, unsigned &NumInputs, SmallVectorImpl< std::pair< void *, bool > > &OpDecls, SmallVectorImpl< std::string > &Constraints, SmallVectorImpl< std::string > &Clobbers, const MCInstrInfo *MII, MCInstPrinter *IP, MCAsmParserSemaCallback &SI)=0
Parse MS-style inline assembly.
MCTargetAsmParser & getTargetParser() const
Definition: MCAsmParser.h:170
virtual void addDirectiveHandler(StringRef Directive, ExtensionDirectiveHandler Handler)=0
Context object for machine code objects.
Definition: MCContext.h:83
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:34
This is an instance of a target assembly language printer that converts an MCInst to valid target ass...
Definition: MCInstPrinter.h:46
Interface to description of machine instruction set.
Definition: MCInstrInfo.h:27
Streaming machine code generation interface.
Definition: MCStreamer.h:220
MCTargetAsmParser - Generic interface to target specific assembly parsers.
Represents a location in source code.
Definition: SMLoc.h:23
Represents a range in source code.
Definition: SMLoc.h:48
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
bool empty() const
Definition: SmallVector.h:82
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
Definition: SourceMgr.h:32
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
LLVM Value Representation.
Definition: Value.h:75
An efficient, type-erasing, non-owning reference to a callable.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1702
LLVM_ABI MCAsmParser * createMCMasmParser(SourceMgr &, MCContext &, MCStreamer &, const MCAsmInfo &, struct tm, unsigned CB=0)
Create an MCAsmParser instance for parsing Microsoft MASM-style assembly.
SourceMgr SrcMgr
Definition: Error.cpp:24
LLVM_ABI MCAsmParser * createMCAsmParser(SourceMgr &, MCContext &, MCStreamer &, const MCAsmInfo &, unsigned CB=0)
Create an MCAsmParser instance for parsing assembly similar to gas syntax.
Definition: AsmParser.cpp:6301
AsmTypeInfo Type
Definition: MCAsmParser.h:104
unsigned ElementSize
Definition: MCAsmParser.h:99
StringRef Name
Definition: MCAsmParser.h:97
void setVar(void *decl, bool isGlobalLV, unsigned size, unsigned type)
Definition: MCAsmParser.h:78
VariableIdentifier Var
Definition: MCAsmParser.h:64
void setLabel(void *decl)
Definition: MCAsmParser.h:73
bool isKind(IdKind kind) const
Definition: MCAsmParser.h:66
void setEnum(int64_t enumVal)
Definition: MCAsmParser.h:68