LLVM 24.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;
27struct ClassReference;
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); }
210
212 CurScope = std::make_unique<TGVarScope>(std::move(CurScope));
213 // Returns a pointer to the new scope, so that the caller can pass it back
214 // to PopScope which will check by assertion that the pushes and pops
215 // match up properly.
216 return CurScope.get();
217 }
219 CurScope = std::make_unique<TGVarScope>(std::move(CurScope), Rec);
220 return CurScope.get();
221 }
223 CurScope = std::make_unique<TGVarScope>(std::move(CurScope), Loop);
224 return CurScope.get();
225 }
227 CurScope = std::make_unique<TGVarScope>(std::move(CurScope), Multiclass);
228 return CurScope.get();
229 }
230 void PopScope(TGVarScope *ExpectedStackTop) {
231 assert(ExpectedStackTop == CurScope.get() &&
232 "Mismatched pushes and pops of local variable scopes");
233 CurScope = CurScope->extractParent();
234 }
235
236private: // Semantic analysis methods.
237 bool AddValue(Record *TheRec, SMLoc Loc, const RecordVal &RV,
238 const Record *FromRec = nullptr);
239 /// Set the value of a RecordVal within the given record. If `OverrideDefLoc`
240 /// is set, the provided location overrides any existing location of the
241 /// RecordVal. An optional `Mode` specifies append/prepend concatenation.
242 bool SetValue(Record *TheRec, SMLoc Loc, const Init *ValName,
243 ArrayRef<unsigned> BitList, const Init *V,
244 bool OverrideDefLoc = true, LetMode Mode = LetMode::Replace);
245 bool AddParentClass(Record *Rec, ClassReference &ParentClass);
246 bool AddParentClass(RecordsEntry &Entry, ClassReference &ParentClass);
247 bool AddParentMultiClass(MultiClassReference &ParentMultiClass);
248
250
251 bool addEntry(RecordsEntry E);
252 bool resolve(const ForeachLoop &Loop, SubstStack &Stack, bool Final,
253 std::vector<RecordsEntry> *Dest, SMLoc *Loc = nullptr);
254 bool resolve(const std::vector<RecordsEntry> &Source, SubstStack &Substs,
255 bool Final, std::vector<RecordsEntry> *Dest,
256 SMLoc *Loc = nullptr);
257 bool addDefOne(std::unique_ptr<Record> Rec);
258
259 using ArgValueHandler = std::function<void(const Init *, const Init *)>;
260 bool resolveArguments(
261 const Record *Rec, ArrayRef<const ArgumentInit *> ArgValues, SMLoc Loc,
262 ArgValueHandler ArgValueHandler = [](const Init *, const Init *) {});
263 bool resolveArgumentsOfClass(MapResolver &R, const Record *Rec,
265 SMLoc Loc);
266 bool resolveArgumentsOfMultiClass(SubstStack &Substs, MultiClass *MC,
268 const Init *DefmName, SMLoc Loc);
269
270private: // Parser methods.
272 bool ParseObjectList();
273 bool ParseObject();
274 bool ParseClass();
275 bool ParseMultiClass();
276 bool ParseDefm();
277 bool ParseDef();
278 bool ParseDefset();
279 bool ParseDeftype();
280 bool ParseDefvar(Record *CurRec = nullptr);
281 bool ParseDump(Record *CurRec = nullptr);
282 bool ParseForeach();
283 bool ParseIf();
284 bool ParseIfBody(StringRef Kind);
285 bool ParseAssert(Record *CurRec = nullptr);
286 bool ParseTopLevelLet();
287 LetModeAndName ParseLetModeAndName();
288 void ParseLetList(SmallVectorImpl<LetRecord> &Result);
289
290 bool ParseObjectBody(Record *CurRec);
291 bool ParseBody(Record *CurRec);
292 bool ParseBodyItem(Record *CurRec);
293
294 bool ParseTemplateArgList(Record *CurRec);
295 bool ParseDeclaration(Record *CurRec, bool ParsingTemplateArgs);
296 const VarInit *ParseForeachDeclaration(const Init *&ForeachListValue);
297
298 ClassReference ParseClassReference(Record *CurRec, bool isDefm);
299 MultiClassReference ParseMultiClassReference();
300
301 const Init *ParseIDValue(Record *CurRec, const StringInit *Name,
302 SMRange NameLoc, IDParseMode Mode = ParseValueMode);
303 const Init *ParseSimpleValue(Record *CurRec, const RecTy *ItemType = nullptr,
304 IDParseMode Mode = ParseValueMode);
305 const Init *ParseValue(Record *CurRec, const RecTy *ItemType = nullptr,
306 IDParseMode Mode = ParseValueMode);
307 void ParseValueList(SmallVectorImpl<const Init *> &Result, Record *CurRec,
308 const RecTy *ItemType = nullptr);
309 bool ParseTemplateArgValueList(SmallVectorImpl<const ArgumentInit *> &Result,
310 SmallVectorImpl<SMLoc> &ArgLocs,
311 Record *CurRec, const Record *ArgsRec);
312 void ParseDagArgList(
313 SmallVectorImpl<std::pair<const Init *, const StringInit *>> &Result,
314 Record *CurRec);
315 bool ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges);
316 const TypedInit *ParseSliceElement(Record *CurRec);
317 const TypedInit *ParseSliceElements(Record *CurRec, bool Single = false);
318 void ParseRangeList(SmallVectorImpl<unsigned> &Result);
319 bool ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
320 const TypedInit *FirstItem = nullptr);
321 const RecTy *ParseType();
322 const Init *ParseOperation(Record *CurRec, const RecTy *ItemType);
323 const Init *ParseOperationSubstr(Record *CurRec, const RecTy *ItemType);
324 const Init *ParseOperationFind(Record *CurRec, const RecTy *ItemType);
325 const Init *ParseOperationListComprehension(Record *CurRec,
326 const RecTy *ItemType);
327 const Init *ParseOperationCond(Record *CurRec, const RecTy *ItemType);
328 const Init *ParseOperationSwitch(Record *CurRec, const RecTy *ItemType);
329 std::optional<const RecTy *> resolveInitTypes(ArrayRef<const Init *> Inits,
330 const Twine &ErrCtx);
331 const RecTy *ParseOperatorType();
332 const Init *ParseObjectName();
333 const Record *ParseClassID();
334 MultiClass *ParseMultiClassID();
335 bool ApplyLetStack(Record *CurRec);
336 bool ApplyLetStack(RecordsEntry &Entry);
337 bool CheckTemplateArgValues(SmallVectorImpl<const ArgumentInit *> &Values,
338 ArrayRef<SMLoc> ValuesLocs,
339 const Record *ArgsRec);
340};
341
342} // end namespace llvm
343
344#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 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")))
const char * Msg
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:1589
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:34
"foo" - Represent an initialization by a string value.
Definition Record.h:715
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TGLexer - TableGen Lexer class.
Definition TGLexer.h:193
void PopScope(TGVarScope *ExpectedStackTop)
Definition TGParser.h:230
bool Error(SMLoc L, const Twine &Msg) const
Definition TGParser.h:205
TGVarScope * PushScope(ForeachLoop *Loop)
Definition TGParser.h:222
TGVarScope * PushScope(Record *Rec)
Definition TGParser.h:218
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:226
bool ParseFile()
ParseFile - Main entrypoint for parsing a tblgen file.
TGVarScope * PushScope()
Definition TGParser.h:211
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:142
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:1262
This is an optimization pass for GlobalISel generic memory operations.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
LLVM_ABI 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:1933
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
#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