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 
12 #include "llvm/ADT/None.h"
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCParser/MCAsmLexer.h"
19 #include "llvm/Support/SMLoc.h"
20 #include <cstdint>
21 #include <ctime>
22 #include <string>
23 #include <utility>
24 
25 namespace llvm {
26 
27 class MCAsmInfo;
28 class MCAsmParserExtension;
29 class MCContext;
30 class MCExpr;
31 class MCInstPrinter;
32 class MCInstrInfo;
33 class MCStreamer;
34 class MCTargetAsmParser;
35 class SourceMgr;
36 
37 struct InlineAsmIdentifierInfo {
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
45   struct EnumIdentifier {
46     int64_t EnumVal;
47   };
48   // Represents a label/function reference
49   struct LabelIdentifier {
50     void *Decl;
51   };
52   // Represents a variable
53   struct VariableIdentifier {
54     void *Decl;
55     bool IsGlobalLV;
56     unsigned Length;
57     unsigned Size;
58     unsigned Type;
59   };
60   // An InlineAsm identifier can only be one of those
61   union {
62     EnumIdentifier Enum;
63     LabelIdentifier Label;
64     VariableIdentifier Var;
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   }
87   InlineAsmIdentifierInfo() : Kind(IK_Invalid) {}
88 
89 private:
90   // Discriminate using the current kind.
91   IdKind Kind;
92 };
93 
94 // Generic type information for an assembly object.
95 // All sizes measured in bytes.
96 struct AsmTypeInfo {
97   StringRef Name;
98   unsigned Size = 0;
99   unsigned ElementSize = 0;
100   unsigned Length = 0;
101 };
102 
103 struct AsmFieldInfo {
104   AsmTypeInfo Type;
105   unsigned Offset = 0;
106 };
107 
108 /// Generic Sema callback for assembly parser.
109 class MCAsmParserSemaCallback {
110 public:
111   virtual ~MCAsmParserSemaCallback();
112 
113   virtual void LookupInlineAsmIdentifier(StringRef &LineBuf,
114                                          InlineAsmIdentifierInfo &Info,
115                                          bool IsUnevaluatedContext) = 0;
116   virtual StringRef LookupInlineAsmLabel(StringRef Identifier, SourceMgr &SM,
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.
124 class MCAsmParser {
125 public:
126   using DirectiveHandler = bool (*)(MCAsmParserExtension*, StringRef, SMLoc);
127   using ExtensionDirectiveHandler =
128       std::pair<MCAsmParserExtension*, DirectiveHandler>;
129 
130   struct MCPendingError {
131     SMLoc Loc;
132     SmallString<64> Msg;
133     SMRange Range;
134   };
135 
136 private:
137   MCTargetAsmParser *TargetParser = nullptr;
138 
139 protected: // Can only create subclasses.
140   MCAsmParser();
141 
142   SmallVector<MCPendingError, 0> PendingErrors;
143 
144   /// Flag tracking whether any errors have been encountered.
145   bool HadError = false;
146 
147   bool ShowParsedOperands = false;
148 
149 public:
150   MCAsmParser(const MCAsmParser &) = delete;
151   MCAsmParser &operator=(const MCAsmParser &) = delete;
152   virtual ~MCAsmParser();
153 
154   virtual void addDirectiveHandler(StringRef Directive,
155                                    ExtensionDirectiveHandler Handler) = 0;
156 
157   virtual void addAliasForDirective(StringRef Directive, StringRef Alias) = 0;
158 
159   virtual SourceMgr &getSourceManager() = 0;
160 
161   virtual MCAsmLexer &getLexer() = 0;
162   const MCAsmLexer &getLexer() const {
163     return const_cast<MCAsmParser*>(this)->getLexer();
164   }
165 
166   virtual MCContext &getContext() = 0;
167 
168   /// Return the output streamer for the assembler.
169   virtual MCStreamer &getStreamer() = 0;
170 
171   MCTargetAsmParser &getTargetParser() const { return *TargetParser; }
172   void setTargetParser(MCTargetAsmParser &P);
173 
174   virtual unsigned getAssemblerDialect() { return 0;}
175   virtual void setAssemblerDialect(unsigned i) { }
176 
177   bool getShowParsedOperands() const { return ShowParsedOperands; }
178   void setShowParsedOperands(bool Value) { ShowParsedOperands = Value; }
179 
180   /// Run the parser on the input source buffer.
181   virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false) = 0;
182 
183   virtual void setParsingMSInlineAsm(bool V) = 0;
184   virtual bool isParsingMSInlineAsm() = 0;
185 
186   virtual bool discardLTOSymbol(StringRef) const { return false; }
187 
188   virtual bool isParsingMasm() const { return false; }
189 
190   virtual bool defineMacro(StringRef Name, StringRef Value) { return true; }
191 
192   virtual bool lookUpField(StringRef Name, AsmFieldInfo &Info) const {
193     return true;
194   }
195   virtual bool lookUpField(StringRef Base, StringRef Member,
196                            AsmFieldInfo &Info) const {
197     return true;
198   }
199 
200   virtual bool lookUpType(StringRef Name, AsmTypeInfo &Info) const {
201     return true;
202   }
203 
204   /// Parse MS-style inline assembly.
205   virtual bool parseMSInlineAsm(
206       std::string &AsmString, unsigned &NumOutputs, unsigned &NumInputs,
207       SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
208       SmallVectorImpl<std::string> &Constraints,
209       SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
210       const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) = 0;
211 
212   /// Emit a note at the location \p L, with the message \p Msg.
213   virtual void Note(SMLoc L, const Twine &Msg, SMRange Range = None) = 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, SMRange Range = None) = 0;
219 
220   /// Return an error at the location \p L, with the message \p Msg. This
221   /// may be modified before being emitted.
222   ///
223   /// \return The return value is always true, as an idiomatic convenience to
224   /// clients.
225   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None);
226 
227   /// Emit an error at the location \p L, with the message \p Msg.
228   ///
229   /// \return The return value is always true, as an idiomatic convenience to
230   /// clients.
231   virtual bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) = 0;
232 
233   bool hasPendingError() { return !PendingErrors.empty(); }
234 
235   bool printPendingErrors() {
236     bool rv = !PendingErrors.empty();
237     for (auto Err : PendingErrors) {
238       printError(Err.Loc, Twine(Err.Msg), Err.Range);
239     }
240     PendingErrors.clear();
241     return rv;
242   }
243 
244   void clearPendingErrors() { PendingErrors.clear(); }
245 
246   bool addErrorSuffix(const Twine &Suffix);
247 
248   /// Get the next AsmToken in the stream, possibly handling file
249   /// inclusion first.
250   virtual const AsmToken &Lex() = 0;
251 
252   /// Get the current AsmToken from the stream.
253   const AsmToken &getTok() const;
254 
255   /// Report an error at the current lexer location.
256   bool TokError(const Twine &Msg, SMRange Range = None);
257 
258   bool parseTokenLoc(SMLoc &Loc);
259   bool parseToken(AsmToken::TokenKind T, const Twine &Msg = "unexpected token");
260   /// Attempt to parse and consume token, returning true on
261   /// success.
262   bool parseOptionalToken(AsmToken::TokenKind T);
263 
264   bool parseComma() { return parseToken(AsmToken::Comma, "expected comma"); }
265   bool parseEOL();
266   bool parseEOL(const Twine &ErrMsg);
267 
268   bool parseMany(function_ref<bool()> parseOne, bool hasComma = true);
269 
270   bool parseIntToken(int64_t &V, const Twine &ErrMsg);
271 
272   bool check(bool P, const Twine &Msg);
273   bool check(bool P, SMLoc Loc, const Twine &Msg);
274 
275   /// Parse an identifier or string (as a quoted identifier) and set \p
276   /// Res to the identifier contents.
277   virtual bool parseIdentifier(StringRef &Res) = 0;
278 
279   /// Parse up to the end of statement and return the contents from the
280   /// current token until the end of the statement; the current token on exit
281   /// will be either the EndOfStatement or EOF.
282   virtual StringRef parseStringToEndOfStatement() = 0;
283 
284   /// Parse the current token as a string which may include escaped
285   /// characters and return the string contents.
286   virtual bool parseEscapedString(std::string &Data) = 0;
287 
288   /// Parse an angle-bracket delimited string at the current position if one is
289   /// present, returning the string contents.
290   virtual bool parseAngleBracketString(std::string &Data) = 0;
291 
292   /// Skip to the end of the current statement, for error recovery.
293   virtual void eatToEndOfStatement() = 0;
294 
295   /// Parse an arbitrary expression.
296   ///
297   /// \param Res - The value of the expression. The result is undefined
298   /// on error.
299   /// \return - False on success.
300   virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) = 0;
301   bool parseExpression(const MCExpr *&Res);
302 
303   /// Parse a primary expression.
304   ///
305   /// \param Res - The value of the expression. The result is undefined
306   /// on error.
307   /// \return - False on success.
308   virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc,
309                                 AsmTypeInfo *TypeInfo) = 0;
310 
311   /// Parse an arbitrary expression, assuming that an initial '(' has
312   /// already been consumed.
313   ///
314   /// \param Res - The value of the expression. The result is undefined
315   /// on error.
316   /// \return - False on success.
317   virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) = 0;
318 
319   /// Parse an expression which must evaluate to an absolute value.
320   ///
321   /// \param Res - The value of the absolute expression. The result is undefined
322   /// on error.
323   /// \return - False on success.
324   virtual bool parseAbsoluteExpression(int64_t &Res) = 0;
325 
326   /// Ensure that we have a valid section set in the streamer. Otherwise,
327   /// report an error and switch to .text.
328   /// \return - False on success.
329   virtual bool checkForValidSection() = 0;
330 
331   /// Parse an arbitrary expression of a specified parenthesis depth,
332   /// assuming that the initial '(' characters have already been consumed.
333   ///
334   /// \param ParenDepth - Specifies how many trailing expressions outside the
335   /// current parentheses we have to parse.
336   /// \param Res - The value of the expression. The result is undefined
337   /// on error.
338   /// \return - False on success.
339   virtual bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
340                                      SMLoc &EndLoc) = 0;
341 
342   /// Parse a .gnu_attribute.
343   bool parseGNUAttribute(SMLoc L, int64_t &Tag, int64_t &IntegerValue);
344 };
345 
346 /// Create an MCAsmParser instance for parsing assembly similar to gas syntax
347 MCAsmParser *createMCAsmParser(SourceMgr &, MCContext &, MCStreamer &,
348                                const MCAsmInfo &, unsigned CB = 0);
349 
350 /// Create an MCAsmParser instance for parsing Microsoft MASM-style assembly
351 MCAsmParser *createMCMasmParser(SourceMgr &, MCContext &, MCStreamer &,
352                                 const MCAsmInfo &, struct tm, unsigned CB = 0);
353 
354 } // end namespace llvm
355 
356 #endif // LLVM_MC_MCPARSER_MCASMPARSER_H
357