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/ADT/Twine.h"
18#include "llvm/Support/SourceMgr.h"
19#include "llvm/TableGen/Error.h"
20#include "llvm/TableGen/Record.h"
21#include <map>
22
23namespace llvm {
24  class Record;
25  class RecordVal;
26  class RecordKeeper;
27  class RecTy;
28  class Init;
29  struct ForeachLoop;
30  struct MultiClass;
31  struct SubClassReference;
32  struct SubMultiClassReference;
33
34  struct LetRecord {
35    StringInit *Name;
36    std::vector<unsigned> Bits;
37    Init *Value;
38    SMLoc Loc;
39    LetRecord(StringInit *N, ArrayRef<unsigned> B, Init *V, SMLoc L)
40      : Name(N), Bits(B), Value(V), Loc(L) {
41    }
42  };
43
44  /// RecordsEntry - Can be either a record or a foreach loop.
45  struct RecordsEntry {
46    std::unique_ptr<Record> Rec;
47    std::unique_ptr<ForeachLoop> Loop;
48
49    void dump() const;
50
51    RecordsEntry() {}
52    RecordsEntry(std::unique_ptr<Record> Rec) : Rec(std::move(Rec)) {}
53    RecordsEntry(std::unique_ptr<ForeachLoop> Loop)
54      : Loop(std::move(Loop)) {}
55  };
56
57  /// ForeachLoop - Record the iteration state associated with a for loop.
58  /// This is used to instantiate items in the loop body.
59  ///
60  /// IterVar is allowed to be null, in which case no iteration variable is
61  /// defined in the loop at all. (This happens when a ForeachLoop is
62  /// constructed by desugaring an if statement.)
63  struct ForeachLoop {
64    SMLoc Loc;
65    VarInit *IterVar;
66    Init *ListValue;
67    std::vector<RecordsEntry> Entries;
68
69    void dump() const;
70
71    ForeachLoop(SMLoc Loc, VarInit *IVar, Init *LValue)
72      : Loc(Loc), IterVar(IVar), ListValue(LValue) {}
73  };
74
75  struct DefsetRecord {
76    SMLoc Loc;
77    RecTy *EltTy = nullptr;
78    SmallVector<Init *, 16> Elements;
79  };
80
81class TGLocalVarScope {
82  // A scope to hold local variable definitions from defvar.
83  std::map<std::string, Init *, std::less<>> vars;
84  std::unique_ptr<TGLocalVarScope> parent;
85
86public:
87  TGLocalVarScope() = default;
88  TGLocalVarScope(std::unique_ptr<TGLocalVarScope> parent)
89      : parent(std::move(parent)) {}
90
91  std::unique_ptr<TGLocalVarScope> extractParent() {
92    // This is expected to be called just before we are destructed, so
93    // it doesn't much matter what state we leave 'parent' in.
94    return std::move(parent);
95  }
96
97  Init *getVar(StringRef Name) const {
98    auto It = vars.find(Name);
99    if (It != vars.end())
100      return It->second;
101    if (parent)
102      return parent->getVar(Name);
103    return nullptr;
104  }
105
106  bool varAlreadyDefined(StringRef Name) const {
107    // When we check whether a variable is already defined, for the purpose of
108    // reporting an error on redefinition, we don't look up to the parent
109    // scope, because it's all right to shadow an outer definition with an
110    // inner one.
111    return vars.find(Name) != vars.end();
112  }
113
114  void addVar(StringRef Name, Init *I) {
115    bool Ins = vars.insert(std::make_pair(Name, I)).second;
116    (void)Ins;
117    assert(Ins && "Local variable already exists");
118  }
119};
120
121struct MultiClass {
122  Record Rec;  // Placeholder for template args and Name.
123  std::vector<RecordsEntry> Entries;
124
125  void dump() const;
126
127  MultiClass(StringRef Name, SMLoc Loc, RecordKeeper &Records) :
128    Rec(Name, Loc, Records) {}
129};
130
131class TGParser {
132  TGLexer Lex;
133  std::vector<SmallVector<LetRecord, 4>> LetStack;
134  std::map<std::string, std::unique_ptr<MultiClass>> MultiClasses;
135
136  /// Loops - Keep track of any foreach loops we are within.
137  ///
138  std::vector<std::unique_ptr<ForeachLoop>> Loops;
139
140  SmallVector<DefsetRecord *, 2> Defsets;
141
142  /// CurMultiClass - If we are parsing a 'multiclass' definition, this is the
143  /// current value.
144  MultiClass *CurMultiClass;
145
146  /// CurLocalScope - Innermost of the current nested scopes for 'defvar' local
147  /// variables.
148  std::unique_ptr<TGLocalVarScope> CurLocalScope;
149
150  // Record tracker
151  RecordKeeper &Records;
152
153  // A "named boolean" indicating how to parse identifiers.  Usually
154  // identifiers map to some existing object but in special cases
155  // (e.g. parsing def names) no such object exists yet because we are
156  // in the middle of creating in.  For those situations, allow the
157  // parser to ignore missing object errors.
158  enum IDParseMode {
159    ParseValueMode,   // We are parsing a value we expect to look up.
160    ParseNameMode,    // We are parsing a name of an object that does not yet
161                      // exist.
162  };
163
164public:
165  TGParser(SourceMgr &SM, ArrayRef<std::string> Macros,
166           RecordKeeper &records)
167    : Lex(SM, Macros), CurMultiClass(nullptr), Records(records) {}
168
169  /// ParseFile - Main entrypoint for parsing a tblgen file.  These parser
170  /// routines return true on error, or false on success.
171  bool ParseFile();
172
173  bool Error(SMLoc L, const Twine &Msg) const {
174    PrintError(L, Msg);
175    return true;
176  }
177  bool TokError(const Twine &Msg) const {
178    return Error(Lex.getLoc(), Msg);
179  }
180  const TGLexer::DependenciesSetTy &getDependencies() const {
181    return Lex.getDependencies();
182  }
183
184  TGLocalVarScope *PushLocalScope() {
185    CurLocalScope = std::make_unique<TGLocalVarScope>(std::move(CurLocalScope));
186    // Returns a pointer to the new scope, so that the caller can pass it back
187    // to PopLocalScope which will check by assertion that the pushes and pops
188    // match up properly.
189    return CurLocalScope.get();
190  }
191  void PopLocalScope(TGLocalVarScope *ExpectedStackTop) {
192    assert(ExpectedStackTop == CurLocalScope.get() &&
193           "Mismatched pushes and pops of local variable scopes");
194    CurLocalScope = CurLocalScope->extractParent();
195  }
196
197private: // Semantic analysis methods.
198  bool AddValue(Record *TheRec, SMLoc Loc, const RecordVal &RV);
199  bool SetValue(Record *TheRec, SMLoc Loc, Init *ValName,
200                ArrayRef<unsigned> BitList, Init *V,
201                bool AllowSelfAssignment = false);
202  bool AddSubClass(Record *Rec, SubClassReference &SubClass);
203  bool AddSubClass(RecordsEntry &Entry, SubClassReference &SubClass);
204  bool AddSubMultiClass(MultiClass *CurMC,
205                        SubMultiClassReference &SubMultiClass);
206
207  using SubstStack = SmallVector<std::pair<Init *, Init *>, 8>;
208
209  bool addEntry(RecordsEntry E);
210  bool resolve(const ForeachLoop &Loop, SubstStack &Stack, bool Final,
211               std::vector<RecordsEntry> *Dest, SMLoc *Loc = nullptr);
212  bool resolve(const std::vector<RecordsEntry> &Source, SubstStack &Substs,
213               bool Final, std::vector<RecordsEntry> *Dest,
214               SMLoc *Loc = nullptr);
215  bool addDefOne(std::unique_ptr<Record> Rec);
216
217private:  // Parser methods.
218  bool ParseObjectList(MultiClass *MC = nullptr);
219  bool ParseObject(MultiClass *MC);
220  bool ParseClass();
221  bool ParseMultiClass();
222  bool ParseDefm(MultiClass *CurMultiClass);
223  bool ParseDef(MultiClass *CurMultiClass);
224  bool ParseDefset();
225  bool ParseDefvar();
226  bool ParseForeach(MultiClass *CurMultiClass);
227  bool ParseIf(MultiClass *CurMultiClass);
228  bool ParseIfBody(MultiClass *CurMultiClass, StringRef Kind);
229  bool ParseTopLevelLet(MultiClass *CurMultiClass);
230  void ParseLetList(SmallVectorImpl<LetRecord> &Result);
231
232  bool ParseObjectBody(Record *CurRec);
233  bool ParseBody(Record *CurRec);
234  bool ParseBodyItem(Record *CurRec);
235
236  bool ParseTemplateArgList(Record *CurRec);
237  Init *ParseDeclaration(Record *CurRec, bool ParsingTemplateArgs);
238  VarInit *ParseForeachDeclaration(Init *&ForeachListValue);
239
240  SubClassReference ParseSubClassReference(Record *CurRec, bool isDefm);
241  SubMultiClassReference ParseSubMultiClassReference(MultiClass *CurMC);
242
243  Init *ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc,
244                     IDParseMode Mode = ParseValueMode);
245  Init *ParseSimpleValue(Record *CurRec, RecTy *ItemType = nullptr,
246                         IDParseMode Mode = ParseValueMode);
247  Init *ParseValue(Record *CurRec, RecTy *ItemType = nullptr,
248                   IDParseMode Mode = ParseValueMode);
249  void ParseValueList(SmallVectorImpl<llvm::Init*> &Result, Record *CurRec,
250                      Record *ArgsRec = nullptr, RecTy *EltTy = nullptr);
251  void ParseDagArgList(
252      SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result,
253      Record *CurRec);
254  bool ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges);
255  bool ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges);
256  void ParseRangeList(SmallVectorImpl<unsigned> &Result);
257  bool ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
258                       TypedInit *FirstItem = nullptr);
259  RecTy *ParseType();
260  Init *ParseOperation(Record *CurRec, RecTy *ItemType);
261  Init *ParseOperationCond(Record *CurRec, RecTy *ItemType);
262  RecTy *ParseOperatorType();
263  Init *ParseObjectName(MultiClass *CurMultiClass);
264  Record *ParseClassID();
265  MultiClass *ParseMultiClassID();
266  bool ApplyLetStack(Record *CurRec);
267  bool ApplyLetStack(RecordsEntry &Entry);
268};
269
270} // end namespace llvm
271
272#endif
273