LLVM 23.0.0git
TGParser.h
Go to the documentation of this file.
1//===- TGParser.h - Parser for TableGen Files -------------------*- 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// This class represents the Parser for tablegen files.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_LIB_TABLEGEN_TGPARSER_H
14#define LLVM_LIB_TABLEGEN_TGPARSER_H
15
16#include "TGLexer.h"
17#include "llvm/TableGen/Error.h"
19#include <map>
20#include <optional>
21
22namespace llvm {
23class SourceMgr;
24class Twine;
25struct ForeachLoop;
26struct MultiClass;
29
30/// Specifies how a 'let' assignment interacts with the existing field value.
31/// - Replace: overwrite the field (default behavior).
32/// - Append: concatenate the new value after the existing value.
33/// - Prepend: concatenate the new value before the existing value.
34enum class LetMode { Replace, Append, Prepend };
35
36/// Parsed let mode keyword and field name (e.g. `let append x` yields
37/// Mode=Append, Name="x"; plain `let x` yields Mode=Replace, Name="x").
40 SMLoc Loc; // Source location of the field name.
41 std::string Name; // The field name being assigned.
42};
43
44struct LetRecord {
46 std::vector<unsigned> Bits;
47 const Init *Value;
52 : Name(N), Bits(B), Value(V), Loc(L), Mode(M) {}
53};
54
55/// RecordsEntry - Holds exactly one of a Record, ForeachLoop, or
56/// AssertionInfo.
58 std::unique_ptr<Record> Rec;
59 std::unique_ptr<ForeachLoop> Loop;
60 std::unique_ptr<Record::AssertionInfo> Assertion;
61 std::unique_ptr<Record::DumpInfo> Dump;
62
63 void dump() const;
64
65 RecordsEntry() = default;
66 RecordsEntry(std::unique_ptr<Record> Rec);
67 RecordsEntry(std::unique_ptr<ForeachLoop> Loop);
68 RecordsEntry(std::unique_ptr<Record::AssertionInfo> Assertion);
69 RecordsEntry(std::unique_ptr<Record::DumpInfo> Dump);
70};
71
72/// ForeachLoop - Record the iteration state associated with a for loop.
73/// This is used to instantiate items in the loop body.
74///
75/// IterVar is allowed to be null, in which case no iteration variable is
76/// defined in the loop at all. (This happens when a ForeachLoop is
77/// constructed by desugaring an if statement.)
82 std::vector<RecordsEntry> Entries;
83
84 void dump() const;
85
86 ForeachLoop(SMLoc Loc, const VarInit *IVar, const Init *LValue)
87 : Loc(Loc), IterVar(IVar), ListValue(LValue) {}
88};
89
95
96struct MultiClass {
97 Record Rec; // Placeholder for template args and Name.
98 std::vector<RecordsEntry> Entries;
99
100 void dump() const;
101
103 : Rec(Name, Loc, Records, Record::RK_MultiClass) {}
104};
105
107public:
109
110private:
111 ScopeKind Kind;
112 std::unique_ptr<TGVarScope> Parent;
113 // A scope to hold variable definitions from defvar.
114 std::map<std::string, const Init *, std::less<>> Vars;
115 Record *CurRec = nullptr;
116 ForeachLoop *CurLoop = nullptr;
117 MultiClass *CurMultiClass = nullptr;
118
119public:
120 TGVarScope(std::unique_ptr<TGVarScope> Parent)
121 : Kind(SK_Local), Parent(std::move(Parent)) {}
122 TGVarScope(std::unique_ptr<TGVarScope> Parent, Record *Rec)
123 : Kind(SK_Record), Parent(std::move(Parent)), CurRec(Rec) {}
124 TGVarScope(std::unique_ptr<TGVarScope> Parent, ForeachLoop *Loop)
125 : Kind(SK_ForeachLoop), Parent(std::move(Parent)), CurLoop(Loop) {}
126 TGVarScope(std::unique_ptr<TGVarScope> Parent, MultiClass *Multiclass)
127 : Kind(SK_MultiClass), Parent(std::move(Parent)),
128 CurMultiClass(Multiclass) {}
129
130 std::unique_ptr<TGVarScope> extractParent() {
131 // This is expected to be called just before we are destructed, so
132 // it doesn't much matter what state we leave 'parent' in.
133 return std::move(Parent);
134 }
135
136 const Init *getVar(RecordKeeper &Records, MultiClass *ParsingMultiClass,
137 const StringInit *Name, SMRange NameLoc,
138 bool TrackReferenceLocs) const;
139
140 bool varAlreadyDefined(StringRef Name) const {
141 // When we check whether a variable is already defined, for the purpose of
142 // reporting an error on redefinition, we don't look up to the parent
143 // scope, because it's all right to shadow an outer definition with an
144 // inner one.
145 return Vars.find(Name) != Vars.end();
146 }
147
148 void addVar(StringRef Name, const Init *I) {
149 bool Ins = Vars.try_emplace(Name.str(), I).second;
150 (void)Ins;
151 assert(Ins && "Local variable already exists");
152 }
153
154 bool isOutermost() const { return Parent == nullptr; }
155};
156
157class TGParser {
158 TGLexer Lex;
159 std::vector<SmallVector<LetRecord, 4>> LetStack;
160 std::map<std::string, std::unique_ptr<MultiClass>> MultiClasses;
161 std::map<std::string, const RecTy *> TypeAliases;
162
163 /// Loops - Keep track of any foreach loops we are within.
164 ///
165 std::vector<std::unique_ptr<ForeachLoop>> Loops;
166
168
169 /// CurMultiClass - If we are parsing a 'multiclass' definition, this is the
170 /// current value.
171 MultiClass *CurMultiClass;
172
173 /// CurScope - Innermost of the current nested scopes for 'defvar' variables.
174 std::unique_ptr<TGVarScope> CurScope;
175
176 // Record tracker
177 RecordKeeper &Records;
178
179 // A "named boolean" indicating how to parse identifiers. Usually
180 // identifiers map to some existing object but in special cases
181 // (e.g. parsing def names) no such object exists yet because we are
182 // in the middle of creating in. For those situations, allow the
183 // parser to ignore missing object errors.
184 enum IDParseMode {
185 ParseValueMode, // We are parsing a value we expect to look up.
186 ParseNameMode, // We are parsing a name of an object that does not yet
187 // exist.
188 };
189
190 bool NoWarnOnUnusedTemplateArgs = false;
191 bool TrackReferenceLocs = false;
192
193public:
195 const bool NoWarnOnUnusedTemplateArgs = false,
196 const bool TrackReferenceLocs = false)
197 : Lex(SM, Macros), CurMultiClass(nullptr), Records(records),
198 NoWarnOnUnusedTemplateArgs(NoWarnOnUnusedTemplateArgs),
199 TrackReferenceLocs(TrackReferenceLocs) {}
200
201 /// ParseFile - Main entrypoint for parsing a tblgen file. These parser
202 /// routines return true on error, or false on success.
203 bool ParseFile();
204
205 bool Error(SMLoc L, const Twine &Msg) const {
206 PrintError(L, Msg);
207 return true;
208 }
209 bool TokError(const Twine &Msg) const { return Error(Lex.getLoc(), Msg); }
211 return Lex.getDependencies();
212 }
213
215 CurScope = std::make_unique<TGVarScope>(std::move(CurScope));
216 // Returns a pointer to the new scope, so that the caller can pass it back
217 // to PopScope which will check by assertion that the pushes and pops
218 // match up properly.
219 return CurScope.get();
220 }
222 CurScope = std::make_unique<TGVarScope>(std::move(CurScope), Rec);
223 return CurScope.get();
224 }
226 CurScope = std::make_unique<TGVarScope>(std::move(CurScope), Loop);
227 return CurScope.get();
228 }
230 CurScope = std::make_unique<TGVarScope>(std::move(CurScope), Multiclass);
231 return CurScope.get();
232 }
233 void PopScope(TGVarScope *ExpectedStackTop) {
234 assert(ExpectedStackTop == CurScope.get() &&
235 "Mismatched pushes and pops of local variable scopes");
236 CurScope = CurScope->extractParent();
237 }
238
239private: // Semantic analysis methods.
240 bool AddValue(Record *TheRec, SMLoc Loc, const RecordVal &RV);
241 /// Set the value of a RecordVal within the given record. If `OverrideDefLoc`
242 /// is set, the provided location overrides any existing location of the
243 /// RecordVal. An optional `Mode` specifies append/prepend concatenation.
244 bool SetValue(Record *TheRec, SMLoc Loc, const Init *ValName,
245 ArrayRef<unsigned> BitList, const Init *V,
246 bool AllowSelfAssignment = false, bool OverrideDefLoc = true,
248 bool AddSubClass(Record *Rec, SubClassReference &SubClass);
249 bool AddSubClass(RecordsEntry &Entry, SubClassReference &SubClass);
250 bool AddSubMultiClass(MultiClass *CurMC,
251 SubMultiClassReference &SubMultiClass);
252
254
255 bool addEntry(RecordsEntry E);
256 bool resolve(const ForeachLoop &Loop, SubstStack &Stack, bool Final,
257 std::vector<RecordsEntry> *Dest, SMLoc *Loc = nullptr);
258 bool resolve(const std::vector<RecordsEntry> &Source, SubstStack &Substs,
259 bool Final, std::vector<RecordsEntry> *Dest,
260 SMLoc *Loc = nullptr);
261 bool addDefOne(std::unique_ptr<Record> Rec);
262
263 using ArgValueHandler = std::function<void(const Init *, const Init *)>;
264 bool resolveArguments(
265 const Record *Rec, ArrayRef<const ArgumentInit *> ArgValues, SMLoc Loc,
266 ArgValueHandler ArgValueHandler = [](const Init *, const Init *) {});
267 bool resolveArgumentsOfClass(MapResolver &R, const Record *Rec,
269 SMLoc Loc);
270 bool resolveArgumentsOfMultiClass(SubstStack &Substs, MultiClass *MC,
272 const Init *DefmName, SMLoc Loc);
273
274private: // Parser methods.
275 bool consume(tgtok::TokKind K);
276 bool ParseObjectList(MultiClass *MC = nullptr);
277 bool ParseObject(MultiClass *MC);
278 bool ParseClass();
279 bool ParseMultiClass();
280 bool ParseDefm(MultiClass *CurMultiClass);
281 bool ParseDef(MultiClass *CurMultiClass);
282 bool ParseDefset();
283 bool ParseDeftype();
284 bool ParseDefvar(Record *CurRec = nullptr);
285 bool ParseDump(MultiClass *CurMultiClass, Record *CurRec = nullptr);
286 bool ParseForeach(MultiClass *CurMultiClass);
287 bool ParseIf(MultiClass *CurMultiClass);
288 bool ParseIfBody(MultiClass *CurMultiClass, StringRef Kind);
289 bool ParseAssert(MultiClass *CurMultiClass, Record *CurRec = nullptr);
290 bool ParseTopLevelLet(MultiClass *CurMultiClass);
291 LetModeAndName ParseLetModeAndName();
292 void ParseLetList(SmallVectorImpl<LetRecord> &Result);
293
294 bool ParseObjectBody(Record *CurRec);
295 bool ParseBody(Record *CurRec);
296 bool ParseBodyItem(Record *CurRec);
297
298 bool ParseTemplateArgList(Record *CurRec);
299 const Init *ParseDeclaration(Record *CurRec, bool ParsingTemplateArgs);
300 const VarInit *ParseForeachDeclaration(const Init *&ForeachListValue);
301
302 SubClassReference ParseSubClassReference(Record *CurRec, bool isDefm);
303 SubMultiClassReference ParseSubMultiClassReference(MultiClass *CurMC);
304
305 const Init *ParseIDValue(Record *CurRec, const StringInit *Name,
306 SMRange NameLoc, IDParseMode Mode = ParseValueMode);
307 const Init *ParseSimpleValue(Record *CurRec, const RecTy *ItemType = nullptr,
308 IDParseMode Mode = ParseValueMode);
309 const Init *ParseValue(Record *CurRec, const RecTy *ItemType = nullptr,
310 IDParseMode Mode = ParseValueMode);
311 void ParseValueList(SmallVectorImpl<const Init *> &Result, Record *CurRec,
312 const RecTy *ItemType = nullptr);
313 bool ParseTemplateArgValueList(SmallVectorImpl<const ArgumentInit *> &Result,
314 SmallVectorImpl<SMLoc> &ArgLocs,
315 Record *CurRec, const Record *ArgsRec);
316 void ParseDagArgList(
317 SmallVectorImpl<std::pair<const Init *, const StringInit *>> &Result,
318 Record *CurRec);
319 bool ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges);
320 bool ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges);
321 const TypedInit *ParseSliceElement(Record *CurRec);
322 const TypedInit *ParseSliceElements(Record *CurRec, bool Single = false);
323 void ParseRangeList(SmallVectorImpl<unsigned> &Result);
324 bool ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
325 const TypedInit *FirstItem = nullptr);
326 const RecTy *ParseType();
327 const Init *ParseOperation(Record *CurRec, const RecTy *ItemType);
328 const Init *ParseOperationSubstr(Record *CurRec, const RecTy *ItemType);
329 const Init *ParseOperationFind(Record *CurRec, const RecTy *ItemType);
330 const Init *ParseOperationListComprehension(Record *CurRec,
331 const RecTy *ItemType);
332 const Init *ParseOperationCond(Record *CurRec, const RecTy *ItemType);
333 const Init *ParseOperationSwitch(Record *CurRec, const RecTy *ItemType);
334 std::optional<const RecTy *> resolveInitTypes(ArrayRef<const Init *> Inits,
335 const Twine &ErrCtx);
336 const RecTy *ParseOperatorType();
337 const Init *ParseObjectName(MultiClass *CurMultiClass);
338 const Record *ParseClassID();
339 MultiClass *ParseMultiClassID();
340 bool ApplyLetStack(Record *CurRec);
341 bool ApplyLetStack(RecordsEntry &Entry);
342 bool CheckTemplateArgValues(SmallVectorImpl<const ArgumentInit *> &Values,
343 ArrayRef<SMLoc> ValuesLocs,
344 const Record *ArgsRec);
345};
346
347} // end namespace llvm
348
349#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF)
Definition Execution.cpp:41
#define I(x, y, z)
Definition MD5.cpp:57
static constexpr unsigned SM(unsigned Version)
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
This class represents a field in a record, including its name, type, value, and source location.
Definition Record.h:1544
Represents a location in source code.
Definition SMLoc.h:22
Represents a range in source code.
Definition SMLoc.h:47
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
Definition SourceMgr.h:37
"foo" - Represent an initialization by a string value.
Definition Record.h:696
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TGLexer - TableGen Lexer class.
Definition TGLexer.h:194
std::set< std::string > DependenciesSetTy
Definition TGLexer.h:211
void PopScope(TGVarScope *ExpectedStackTop)
Definition TGParser.h:233
const TGLexer::DependenciesSetTy & getDependencies() const
Definition TGParser.h:210
bool Error(SMLoc L, const Twine &Msg) const
Definition TGParser.h:205
TGVarScope * PushScope(ForeachLoop *Loop)
Definition TGParser.h:225
TGVarScope * PushScope(Record *Rec)
Definition TGParser.h:221
bool TokError(const Twine &Msg) const
Definition TGParser.h:209
TGParser(SourceMgr &SM, ArrayRef< std::string > Macros, RecordKeeper &records, const bool NoWarnOnUnusedTemplateArgs=false, const bool TrackReferenceLocs=false)
Definition TGParser.h:194
TGVarScope * PushScope(MultiClass *Multiclass)
Definition TGParser.h:229
bool ParseFile()
ParseFile - Main entrypoint for parsing a tblgen file.
TGVarScope * PushScope()
Definition TGParser.h:214
TGVarScope(std::unique_ptr< TGVarScope > Parent, Record *Rec)
Definition TGParser.h:122
std::unique_ptr< TGVarScope > extractParent()
Definition TGParser.h:130
bool isOutermost() const
Definition TGParser.h:154
TGVarScope(std::unique_ptr< TGVarScope > Parent, ForeachLoop *Loop)
Definition TGParser.h:124
void addVar(StringRef Name, const Init *I)
Definition TGParser.h:148
bool varAlreadyDefined(StringRef Name) const
Definition TGParser.h:140
const Init * getVar(RecordKeeper &Records, MultiClass *ParsingMultiClass, const StringInit *Name, SMRange NameLoc, bool TrackReferenceLocs) const
Definition TGParser.cpp:147
TGVarScope(std::unique_ptr< TGVarScope > Parent, MultiClass *Multiclass)
Definition TGParser.h:126
TGVarScope(std::unique_ptr< TGVarScope > Parent)
Definition TGParser.h:120
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
'Opcode' - Represent a reference to an entire variable object.
Definition Record.h:1223
This is an optimization pass for GlobalISel generic memory operations.
void PrintError(const Twine &Msg)
Definition Error.cpp:104
LetMode
Specifies how a 'let' assignment interacts with the existing field value.
Definition TGParser.h:34
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1916
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:874
#define N
const RecTy * EltTy
Definition TGParser.h:92
SmallVector< Init *, 16 > Elements
Definition TGParser.h:93
ForeachLoop - Record the iteration state associated with a for loop.
Definition TGParser.h:78
ForeachLoop(SMLoc Loc, const VarInit *IVar, const Init *LValue)
Definition TGParser.h:86
std::vector< RecordsEntry > Entries
Definition TGParser.h:82
const Init * ListValue
Definition TGParser.h:81
void dump() const
const VarInit * IterVar
Definition TGParser.h:80
Parsed let mode keyword and field name (e.g.
Definition TGParser.h:38
std::string Name
Definition TGParser.h:41
LetRecord(const StringInit *N, ArrayRef< unsigned > B, const Init *V, SMLoc L, LetMode M=LetMode::Replace)
Definition TGParser.h:50
const Init * Value
Definition TGParser.h:47
const StringInit * Name
Definition TGParser.h:45
std::vector< unsigned > Bits
Definition TGParser.h:46
LetMode Mode
Definition TGParser.h:49
std::vector< RecordsEntry > Entries
Definition TGParser.h:98
void dump() const
MultiClass(StringRef Name, SMLoc Loc, RecordKeeper &Records)
Definition TGParser.h:102
RecordsEntry - Holds exactly one of a Record, ForeachLoop, or AssertionInfo.
Definition TGParser.h:57
RecordsEntry()=default
std::unique_ptr< ForeachLoop > Loop
Definition TGParser.h:59
std::unique_ptr< Record::AssertionInfo > Assertion
Definition TGParser.h:60
void dump() const
std::unique_ptr< Record::DumpInfo > Dump
Definition TGParser.h:61
std::unique_ptr< Record > Rec
Definition TGParser.h:58