xref: /freebsd/contrib/llvm-project/llvm/include/llvm/TableGen/Record.h (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1 //===- llvm/TableGen/Record.h - Classes for Table Records -------*- 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 file defines the main TableGen data structures, including the TableGen
10 // types, values, and high-level data structures.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_TABLEGEN_RECORD_H
15 #define LLVM_TABLEGEN_RECORD_H
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/PointerIntPair.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/Support/Casting.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/SMLoc.h"
28 #include "llvm/Support/Timer.h"
29 #include "llvm/Support/TrailingObjects.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <cassert>
32 #include <cstddef>
33 #include <cstdint>
34 #include <map>
35 #include <memory>
36 #include <optional>
37 #include <string>
38 #include <utility>
39 #include <variant>
40 #include <vector>
41 
42 namespace llvm {
43 namespace detail {
44 struct RecordKeeperImpl;
45 } // namespace detail
46 
47 class ListRecTy;
48 class Record;
49 class RecordKeeper;
50 class RecordVal;
51 class Resolver;
52 class StringInit;
53 class TypedInit;
54 
55 //===----------------------------------------------------------------------===//
56 //  Type Classes
57 //===----------------------------------------------------------------------===//
58 
59 class RecTy {
60 public:
61   /// Subclass discriminator (for dyn_cast<> et al.)
62   enum RecTyKind {
63     BitRecTyKind,
64     BitsRecTyKind,
65     IntRecTyKind,
66     StringRecTyKind,
67     ListRecTyKind,
68     DagRecTyKind,
69     RecordRecTyKind
70   };
71 
72 private:
73   RecTyKind Kind;
74   /// The RecordKeeper that uniqued this Type.
75   RecordKeeper &RK;
76   /// ListRecTy of the list that has elements of this type.
77   ListRecTy *ListTy = nullptr;
78 
79 public:
RecTy(RecTyKind K,RecordKeeper & RK)80   RecTy(RecTyKind K, RecordKeeper &RK) : Kind(K), RK(RK) {}
81   virtual ~RecTy() = default;
82 
getRecTyKind()83   RecTyKind getRecTyKind() const { return Kind; }
84 
85   /// Return the RecordKeeper that uniqued this Type.
getRecordKeeper()86   RecordKeeper &getRecordKeeper() const { return RK; }
87 
88   virtual std::string getAsString() const = 0;
print(raw_ostream & OS)89   void print(raw_ostream &OS) const { OS << getAsString(); }
90   void dump() const;
91 
92   /// Return true if all values of 'this' type can be converted to the specified
93   /// type.
94   virtual bool typeIsConvertibleTo(const RecTy *RHS) const;
95 
96   /// Return true if 'this' type is equal to or a subtype of RHS. For example,
97   /// a bit set is not an int, but they are convertible.
98   virtual bool typeIsA(const RecTy *RHS) const;
99 
100   /// Returns the type representing list<thistype>.
101   ListRecTy *getListTy();
102 };
103 
104 inline raw_ostream &operator<<(raw_ostream &OS, const RecTy &Ty) {
105   Ty.print(OS);
106   return OS;
107 }
108 
109 /// 'bit' - Represent a single bit
110 class BitRecTy : public RecTy {
111   friend detail::RecordKeeperImpl;
112 
BitRecTy(RecordKeeper & RK)113   BitRecTy(RecordKeeper &RK) : RecTy(BitRecTyKind, RK) {}
114 
115 public:
classof(const RecTy * RT)116   static bool classof(const RecTy *RT) {
117     return RT->getRecTyKind() == BitRecTyKind;
118   }
119 
120   static BitRecTy *get(RecordKeeper &RK);
121 
getAsString()122   std::string getAsString() const override { return "bit"; }
123 
124   bool typeIsConvertibleTo(const RecTy *RHS) const override;
125 };
126 
127 /// 'bits<n>' - Represent a fixed number of bits
128 class BitsRecTy : public RecTy {
129   unsigned Size;
130 
BitsRecTy(RecordKeeper & RK,unsigned Sz)131   explicit BitsRecTy(RecordKeeper &RK, unsigned Sz)
132       : RecTy(BitsRecTyKind, RK), Size(Sz) {}
133 
134 public:
classof(const RecTy * RT)135   static bool classof(const RecTy *RT) {
136     return RT->getRecTyKind() == BitsRecTyKind;
137   }
138 
139   static BitsRecTy *get(RecordKeeper &RK, unsigned Sz);
140 
getNumBits()141   unsigned getNumBits() const { return Size; }
142 
143   std::string getAsString() const override;
144 
145   bool typeIsConvertibleTo(const RecTy *RHS) const override;
146 };
147 
148 /// 'int' - Represent an integer value of no particular size
149 class IntRecTy : public RecTy {
150   friend detail::RecordKeeperImpl;
151 
IntRecTy(RecordKeeper & RK)152   IntRecTy(RecordKeeper &RK) : RecTy(IntRecTyKind, RK) {}
153 
154 public:
classof(const RecTy * RT)155   static bool classof(const RecTy *RT) {
156     return RT->getRecTyKind() == IntRecTyKind;
157   }
158 
159   static IntRecTy *get(RecordKeeper &RK);
160 
getAsString()161   std::string getAsString() const override { return "int"; }
162 
163   bool typeIsConvertibleTo(const RecTy *RHS) const override;
164 };
165 
166 /// 'string' - Represent an string value
167 class StringRecTy : public RecTy {
168   friend detail::RecordKeeperImpl;
169 
StringRecTy(RecordKeeper & RK)170   StringRecTy(RecordKeeper &RK) : RecTy(StringRecTyKind, RK) {}
171 
172 public:
classof(const RecTy * RT)173   static bool classof(const RecTy *RT) {
174     return RT->getRecTyKind() == StringRecTyKind;
175   }
176 
177   static StringRecTy *get(RecordKeeper &RK);
178 
179   std::string getAsString() const override;
180 
181   bool typeIsConvertibleTo(const RecTy *RHS) const override;
182 };
183 
184 /// 'list<Ty>' - Represent a list of element values, all of which must be of
185 /// the specified type. The type is stored in ElementTy.
186 class ListRecTy : public RecTy {
187   friend ListRecTy *RecTy::getListTy();
188 
189   RecTy *ElementTy;
190 
ListRecTy(RecTy * T)191   explicit ListRecTy(RecTy *T)
192       : RecTy(ListRecTyKind, T->getRecordKeeper()), ElementTy(T) {}
193 
194 public:
classof(const RecTy * RT)195   static bool classof(const RecTy *RT) {
196     return RT->getRecTyKind() == ListRecTyKind;
197   }
198 
get(RecTy * T)199   static ListRecTy *get(RecTy *T) { return T->getListTy(); }
getElementType()200   RecTy *getElementType() const { return ElementTy; }
201 
202   std::string getAsString() const override;
203 
204   bool typeIsConvertibleTo(const RecTy *RHS) const override;
205 
206   bool typeIsA(const RecTy *RHS) const override;
207 };
208 
209 /// 'dag' - Represent a dag fragment
210 class DagRecTy : public RecTy {
211   friend detail::RecordKeeperImpl;
212 
DagRecTy(RecordKeeper & RK)213   DagRecTy(RecordKeeper &RK) : RecTy(DagRecTyKind, RK) {}
214 
215 public:
classof(const RecTy * RT)216   static bool classof(const RecTy *RT) {
217     return RT->getRecTyKind() == DagRecTyKind;
218   }
219 
220   static DagRecTy *get(RecordKeeper &RK);
221 
222   std::string getAsString() const override;
223 };
224 
225 /// '[classname]' - Type of record values that have zero or more superclasses.
226 ///
227 /// The list of superclasses is non-redundant, i.e. only contains classes that
228 /// are not the superclass of some other listed class.
229 class RecordRecTy final : public RecTy, public FoldingSetNode,
230                           public TrailingObjects<RecordRecTy, Record *> {
231   friend class Record;
232   friend detail::RecordKeeperImpl;
233 
234   unsigned NumClasses;
235 
RecordRecTy(RecordKeeper & RK,unsigned Num)236   explicit RecordRecTy(RecordKeeper &RK, unsigned Num)
237       : RecTy(RecordRecTyKind, RK), NumClasses(Num) {}
238 
239 public:
240   RecordRecTy(const RecordRecTy &) = delete;
241   RecordRecTy &operator=(const RecordRecTy &) = delete;
242 
243   // Do not use sized deallocation due to trailing objects.
delete(void * p)244   void operator delete(void *p) { ::operator delete(p); }
245 
classof(const RecTy * RT)246   static bool classof(const RecTy *RT) {
247     return RT->getRecTyKind() == RecordRecTyKind;
248   }
249 
250   /// Get the record type with the given non-redundant list of superclasses.
251   static RecordRecTy *get(RecordKeeper &RK, ArrayRef<Record *> Classes);
252   static RecordRecTy *get(Record *Class);
253 
254   void Profile(FoldingSetNodeID &ID) const;
255 
getClasses()256   ArrayRef<Record *> getClasses() const {
257     return ArrayRef(getTrailingObjects<Record *>(), NumClasses);
258   }
259 
260   using const_record_iterator = Record * const *;
261 
classes_begin()262   const_record_iterator classes_begin() const { return getClasses().begin(); }
classes_end()263   const_record_iterator classes_end() const { return getClasses().end(); }
264 
265   std::string getAsString() const override;
266 
267   bool isSubClassOf(Record *Class) const;
268   bool typeIsConvertibleTo(const RecTy *RHS) const override;
269 
270   bool typeIsA(const RecTy *RHS) const override;
271 };
272 
273 /// Find a common type that T1 and T2 convert to.
274 /// Return 0 if no such type exists.
275 RecTy *resolveTypes(RecTy *T1, RecTy *T2);
276 
277 //===----------------------------------------------------------------------===//
278 //  Initializer Classes
279 //===----------------------------------------------------------------------===//
280 
281 class Init {
282 protected:
283   /// Discriminator enum (for isa<>, dyn_cast<>, et al.)
284   ///
285   /// This enum is laid out by a preorder traversal of the inheritance
286   /// hierarchy, and does not contain an entry for abstract classes, as per
287   /// the recommendation in docs/HowToSetUpLLVMStyleRTTI.rst.
288   ///
289   /// We also explicitly include "first" and "last" values for each
290   /// interior node of the inheritance tree, to make it easier to read the
291   /// corresponding classof().
292   ///
293   /// We could pack these a bit tighter by not having the IK_FirstXXXInit
294   /// and IK_LastXXXInit be their own values, but that would degrade
295   /// readability for really no benefit.
296   enum InitKind : uint8_t {
297     IK_First, // unused; silence a spurious warning
298     IK_FirstTypedInit,
299     IK_BitInit,
300     IK_BitsInit,
301     IK_DagInit,
302     IK_DefInit,
303     IK_FieldInit,
304     IK_IntInit,
305     IK_ListInit,
306     IK_FirstOpInit,
307     IK_BinOpInit,
308     IK_TernOpInit,
309     IK_UnOpInit,
310     IK_LastOpInit,
311     IK_CondOpInit,
312     IK_FoldOpInit,
313     IK_IsAOpInit,
314     IK_ExistsOpInit,
315     IK_AnonymousNameInit,
316     IK_StringInit,
317     IK_VarInit,
318     IK_VarBitInit,
319     IK_VarDefInit,
320     IK_LastTypedInit,
321     IK_UnsetInit,
322     IK_ArgumentInit,
323   };
324 
325 private:
326   const InitKind Kind;
327 
328 protected:
329   uint8_t Opc; // Used by UnOpInit, BinOpInit, and TernOpInit
330 
331 private:
332   virtual void anchor();
333 
334 public:
335   /// Get the kind (type) of the value.
getKind()336   InitKind getKind() const { return Kind; }
337 
338   /// Get the record keeper that initialized this Init.
339   RecordKeeper &getRecordKeeper() const;
340 
341 protected:
Kind(K)342   explicit Init(InitKind K, uint8_t Opc = 0) : Kind(K), Opc(Opc) {}
343 
344 public:
345   Init(const Init &) = delete;
346   Init &operator=(const Init &) = delete;
347   virtual ~Init() = default;
348 
349   /// Is this a complete value with no unset (uninitialized) subvalues?
isComplete()350   virtual bool isComplete() const { return true; }
351 
352   /// Is this a concrete and fully resolved value without any references or
353   /// stuck operations? Unset values are concrete.
isConcrete()354   virtual bool isConcrete() const { return false; }
355 
356   /// Print this value.
print(raw_ostream & OS)357   void print(raw_ostream &OS) const { OS << getAsString(); }
358 
359   /// Convert this value to a literal form.
360   virtual std::string getAsString() const = 0;
361 
362   /// Convert this value to a literal form,
363   /// without adding quotes around a string.
getAsUnquotedString()364   virtual std::string getAsUnquotedString() const { return getAsString(); }
365 
366   /// Debugging method that may be called through a debugger; just
367   /// invokes print on stderr.
368   void dump() const;
369 
370   /// If this value is convertible to type \p Ty, return a value whose
371   /// type is \p Ty, generating a !cast operation if required.
372   /// Otherwise, return null.
373   virtual Init *getCastTo(RecTy *Ty) const = 0;
374 
375   /// Convert to a value whose type is \p Ty, or return null if this
376   /// is not possible. This can happen if the value's type is convertible
377   /// to \p Ty, but there are unresolved references.
378   virtual Init *convertInitializerTo(RecTy *Ty) const = 0;
379 
380   /// This function is used to implement the bit range
381   /// selection operator. Given a value, it selects the specified bits,
382   /// returning them as a new \p Init of type \p bits. If it is not legal
383   /// to use the bit selection operator on this value, null is returned.
convertInitializerBitRange(ArrayRef<unsigned> Bits)384   virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
385     return nullptr;
386   }
387 
388   /// This function is used to implement the FieldInit class.
389   /// Implementors of this method should return the type of the named
390   /// field if they are of type record.
getFieldType(StringInit * FieldName)391   virtual RecTy *getFieldType(StringInit *FieldName) const {
392     return nullptr;
393   }
394 
395   /// This function is used by classes that refer to other
396   /// variables which may not be defined at the time the expression is formed.
397   /// If a value is set for the variable later, this method will be called on
398   /// users of the value to allow the value to propagate out.
resolveReferences(Resolver & R)399   virtual Init *resolveReferences(Resolver &R) const {
400     return const_cast<Init *>(this);
401   }
402 
403   /// Get the \p Init value of the specified bit.
404   virtual Init *getBit(unsigned Bit) const = 0;
405 };
406 
407 inline raw_ostream &operator<<(raw_ostream &OS, const Init &I) {
408   I.print(OS); return OS;
409 }
410 
411 /// This is the common superclass of types that have a specific,
412 /// explicit type, stored in ValueTy.
413 class TypedInit : public Init {
414   RecTy *ValueTy;
415 
416 protected:
417   explicit TypedInit(InitKind K, RecTy *T, uint8_t Opc = 0)
Init(K,Opc)418       : Init(K, Opc), ValueTy(T) {}
419 
420 public:
421   TypedInit(const TypedInit &) = delete;
422   TypedInit &operator=(const TypedInit &) = delete;
423 
classof(const Init * I)424   static bool classof(const Init *I) {
425     return I->getKind() >= IK_FirstTypedInit &&
426            I->getKind() <= IK_LastTypedInit;
427   }
428 
429   /// Get the type of the Init as a RecTy.
getType()430   RecTy *getType() const { return ValueTy; }
431 
432   /// Get the record keeper that initialized this Init.
getRecordKeeper()433   RecordKeeper &getRecordKeeper() const { return ValueTy->getRecordKeeper(); }
434 
435   Init *getCastTo(RecTy *Ty) const override;
436   Init *convertInitializerTo(RecTy *Ty) const override;
437 
438   Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
439 
440   /// This method is used to implement the FieldInit class.
441   /// Implementors of this method should return the type of the named field if
442   /// they are of type record.
443   RecTy *getFieldType(StringInit *FieldName) const override;
444 };
445 
446 /// '?' - Represents an uninitialized value.
447 class UnsetInit : public Init {
448   friend detail::RecordKeeperImpl;
449 
450   /// The record keeper that initialized this Init.
451   RecordKeeper &RK;
452 
UnsetInit(RecordKeeper & RK)453   UnsetInit(RecordKeeper &RK) : Init(IK_UnsetInit), RK(RK) {}
454 
455 public:
456   UnsetInit(const UnsetInit &) = delete;
457   UnsetInit &operator=(const UnsetInit &) = delete;
458 
classof(const Init * I)459   static bool classof(const Init *I) {
460     return I->getKind() == IK_UnsetInit;
461   }
462 
463   /// Get the singleton unset Init.
464   static UnsetInit *get(RecordKeeper &RK);
465 
466   /// Get the record keeper that initialized this Init.
getRecordKeeper()467   RecordKeeper &getRecordKeeper() const { return RK; }
468 
469   Init *getCastTo(RecTy *Ty) const override;
470   Init *convertInitializerTo(RecTy *Ty) const override;
471 
getBit(unsigned Bit)472   Init *getBit(unsigned Bit) const override {
473     return const_cast<UnsetInit*>(this);
474   }
475 
476   /// Is this a complete value with no unset (uninitialized) subvalues?
isComplete()477   bool isComplete() const override { return false; }
478 
isConcrete()479   bool isConcrete() const override { return true; }
480 
481   /// Get the string representation of the Init.
getAsString()482   std::string getAsString() const override { return "?"; }
483 };
484 
485 // Represent an argument.
486 using ArgAuxType = std::variant<unsigned, Init *>;
487 class ArgumentInit : public Init, public FoldingSetNode {
488 public:
489   enum Kind {
490     Positional,
491     Named,
492   };
493 
494 private:
495   Init *Value;
496   ArgAuxType Aux;
497 
498 protected:
ArgumentInit(Init * Value,ArgAuxType Aux)499   explicit ArgumentInit(Init *Value, ArgAuxType Aux)
500       : Init(IK_ArgumentInit), Value(Value), Aux(Aux) {}
501 
502 public:
503   ArgumentInit(const ArgumentInit &) = delete;
504   ArgumentInit &operator=(const ArgumentInit &) = delete;
505 
classof(const Init * I)506   static bool classof(const Init *I) { return I->getKind() == IK_ArgumentInit; }
507 
getRecordKeeper()508   RecordKeeper &getRecordKeeper() const { return Value->getRecordKeeper(); }
509 
510   static ArgumentInit *get(Init *Value, ArgAuxType Aux);
511 
isPositional()512   bool isPositional() const { return Aux.index() == Positional; }
isNamed()513   bool isNamed() const { return Aux.index() == Named; }
514 
getValue()515   Init *getValue() const { return Value; }
getIndex()516   unsigned getIndex() const {
517     assert(isPositional() && "Should be positional!");
518     return std::get<Positional>(Aux);
519   }
getName()520   Init *getName() const {
521     assert(isNamed() && "Should be named!");
522     return std::get<Named>(Aux);
523   }
cloneWithValue(Init * Value)524   ArgumentInit *cloneWithValue(Init *Value) const { return get(Value, Aux); }
525 
526   void Profile(FoldingSetNodeID &ID) const;
527 
528   Init *resolveReferences(Resolver &R) const override;
getAsString()529   std::string getAsString() const override {
530     if (isPositional())
531       return utostr(getIndex()) + ": " + Value->getAsString();
532     if (isNamed())
533       return getName()->getAsString() + ": " + Value->getAsString();
534     llvm_unreachable("Unsupported argument type!");
535     return "";
536   }
537 
isComplete()538   bool isComplete() const override { return false; }
isConcrete()539   bool isConcrete() const override { return false; }
getBit(unsigned Bit)540   Init *getBit(unsigned Bit) const override { return Value->getBit(Bit); }
getCastTo(RecTy * Ty)541   Init *getCastTo(RecTy *Ty) const override { return Value->getCastTo(Ty); }
convertInitializerTo(RecTy * Ty)542   Init *convertInitializerTo(RecTy *Ty) const override {
543     return Value->convertInitializerTo(Ty);
544   }
545 };
546 
547 /// 'true'/'false' - Represent a concrete initializer for a bit.
548 class BitInit final : public TypedInit {
549   friend detail::RecordKeeperImpl;
550 
551   bool Value;
552 
BitInit(bool V,RecTy * T)553   explicit BitInit(bool V, RecTy *T) : TypedInit(IK_BitInit, T), Value(V) {}
554 
555 public:
556   BitInit(const BitInit &) = delete;
557   BitInit &operator=(BitInit &) = delete;
558 
classof(const Init * I)559   static bool classof(const Init *I) {
560     return I->getKind() == IK_BitInit;
561   }
562 
563   static BitInit *get(RecordKeeper &RK, bool V);
564 
getValue()565   bool getValue() const { return Value; }
566 
567   Init *convertInitializerTo(RecTy *Ty) const override;
568 
getBit(unsigned Bit)569   Init *getBit(unsigned Bit) const override {
570     assert(Bit < 1 && "Bit index out of range!");
571     return const_cast<BitInit*>(this);
572   }
573 
isConcrete()574   bool isConcrete() const override { return true; }
getAsString()575   std::string getAsString() const override { return Value ? "1" : "0"; }
576 };
577 
578 /// '{ a, b, c }' - Represents an initializer for a BitsRecTy value.
579 /// It contains a vector of bits, whose size is determined by the type.
580 class BitsInit final : public TypedInit, public FoldingSetNode,
581                        public TrailingObjects<BitsInit, Init *> {
582   unsigned NumBits;
583 
BitsInit(RecordKeeper & RK,unsigned N)584   BitsInit(RecordKeeper &RK, unsigned N)
585       : TypedInit(IK_BitsInit, BitsRecTy::get(RK, N)), NumBits(N) {}
586 
587 public:
588   BitsInit(const BitsInit &) = delete;
589   BitsInit &operator=(const BitsInit &) = delete;
590 
591   // Do not use sized deallocation due to trailing objects.
delete(void * p)592   void operator delete(void *p) { ::operator delete(p); }
593 
classof(const Init * I)594   static bool classof(const Init *I) {
595     return I->getKind() == IK_BitsInit;
596   }
597 
598   static BitsInit *get(RecordKeeper &RK, ArrayRef<Init *> Range);
599 
600   void Profile(FoldingSetNodeID &ID) const;
601 
getNumBits()602   unsigned getNumBits() const { return NumBits; }
603 
604   Init *convertInitializerTo(RecTy *Ty) const override;
605   Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
606 
isComplete()607   bool isComplete() const override {
608     for (unsigned i = 0; i != getNumBits(); ++i)
609       if (!getBit(i)->isComplete()) return false;
610     return true;
611   }
612 
allInComplete()613   bool allInComplete() const {
614     for (unsigned i = 0; i != getNumBits(); ++i)
615       if (getBit(i)->isComplete()) return false;
616     return true;
617   }
618 
619   bool isConcrete() const override;
620   std::string getAsString() const override;
621 
622   Init *resolveReferences(Resolver &R) const override;
623 
getBit(unsigned Bit)624   Init *getBit(unsigned Bit) const override {
625     assert(Bit < NumBits && "Bit index out of range!");
626     return getTrailingObjects<Init *>()[Bit];
627   }
628 };
629 
630 /// '7' - Represent an initialization by a literal integer value.
631 class IntInit : public TypedInit {
632   int64_t Value;
633 
IntInit(RecordKeeper & RK,int64_t V)634   explicit IntInit(RecordKeeper &RK, int64_t V)
635       : TypedInit(IK_IntInit, IntRecTy::get(RK)), Value(V) {}
636 
637 public:
638   IntInit(const IntInit &) = delete;
639   IntInit &operator=(const IntInit &) = delete;
640 
classof(const Init * I)641   static bool classof(const Init *I) {
642     return I->getKind() == IK_IntInit;
643   }
644 
645   static IntInit *get(RecordKeeper &RK, int64_t V);
646 
getValue()647   int64_t getValue() const { return Value; }
648 
649   Init *convertInitializerTo(RecTy *Ty) const override;
650   Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
651 
isConcrete()652   bool isConcrete() const override { return true; }
653   std::string getAsString() const override;
654 
getBit(unsigned Bit)655   Init *getBit(unsigned Bit) const override {
656     return BitInit::get(getRecordKeeper(), (Value & (1ULL << Bit)) != 0);
657   }
658 };
659 
660 /// "anonymous_n" - Represent an anonymous record name
661 class AnonymousNameInit : public TypedInit {
662   unsigned Value;
663 
AnonymousNameInit(RecordKeeper & RK,unsigned V)664   explicit AnonymousNameInit(RecordKeeper &RK, unsigned V)
665       : TypedInit(IK_AnonymousNameInit, StringRecTy::get(RK)), Value(V) {}
666 
667 public:
668   AnonymousNameInit(const AnonymousNameInit &) = delete;
669   AnonymousNameInit &operator=(const AnonymousNameInit &) = delete;
670 
classof(const Init * I)671   static bool classof(const Init *I) {
672     return I->getKind() == IK_AnonymousNameInit;
673   }
674 
675   static AnonymousNameInit *get(RecordKeeper &RK, unsigned);
676 
getValue()677   unsigned getValue() const { return Value; }
678 
679   StringInit *getNameInit() const;
680 
681   std::string getAsString() const override;
682 
683   Init *resolveReferences(Resolver &R) const override;
684 
getBit(unsigned Bit)685   Init *getBit(unsigned Bit) const override {
686     llvm_unreachable("Illegal bit reference off string");
687   }
688 };
689 
690 /// "foo" - Represent an initialization by a string value.
691 class StringInit : public TypedInit {
692 public:
693   enum StringFormat {
694     SF_String, // Format as "text"
695     SF_Code,   // Format as [{text}]
696   };
697 
698 private:
699   StringRef Value;
700   StringFormat Format;
701 
StringInit(RecordKeeper & RK,StringRef V,StringFormat Fmt)702   explicit StringInit(RecordKeeper &RK, StringRef V, StringFormat Fmt)
703       : TypedInit(IK_StringInit, StringRecTy::get(RK)), Value(V), Format(Fmt) {}
704 
705 public:
706   StringInit(const StringInit &) = delete;
707   StringInit &operator=(const StringInit &) = delete;
708 
classof(const Init * I)709   static bool classof(const Init *I) {
710     return I->getKind() == IK_StringInit;
711   }
712 
713   static StringInit *get(RecordKeeper &RK, StringRef,
714                          StringFormat Fmt = SF_String);
715 
determineFormat(StringFormat Fmt1,StringFormat Fmt2)716   static StringFormat determineFormat(StringFormat Fmt1, StringFormat Fmt2) {
717     return (Fmt1 == SF_Code || Fmt2 == SF_Code) ? SF_Code : SF_String;
718   }
719 
getValue()720   StringRef getValue() const { return Value; }
getFormat()721   StringFormat getFormat() const { return Format; }
hasCodeFormat()722   bool hasCodeFormat() const { return Format == SF_Code; }
723 
724   Init *convertInitializerTo(RecTy *Ty) const override;
725 
isConcrete()726   bool isConcrete() const override { return true; }
727 
getAsString()728   std::string getAsString() const override {
729     if (Format == SF_String)
730       return "\"" + Value.str() + "\"";
731     else
732       return "[{" + Value.str() + "}]";
733   }
734 
getAsUnquotedString()735   std::string getAsUnquotedString() const override {
736     return std::string(Value);
737   }
738 
getBit(unsigned Bit)739   Init *getBit(unsigned Bit) const override {
740     llvm_unreachable("Illegal bit reference off string");
741   }
742 };
743 
744 /// [AL, AH, CL] - Represent a list of defs
745 ///
746 class ListInit final : public TypedInit, public FoldingSetNode,
747                        public TrailingObjects<ListInit, Init *> {
748   unsigned NumValues;
749 
750 public:
751   using const_iterator = Init *const *;
752 
753 private:
ListInit(unsigned N,RecTy * EltTy)754   explicit ListInit(unsigned N, RecTy *EltTy)
755       : TypedInit(IK_ListInit, ListRecTy::get(EltTy)), NumValues(N) {}
756 
757 public:
758   ListInit(const ListInit &) = delete;
759   ListInit &operator=(const ListInit &) = delete;
760 
761   // Do not use sized deallocation due to trailing objects.
delete(void * p)762   void operator delete(void *p) { ::operator delete(p); }
763 
classof(const Init * I)764   static bool classof(const Init *I) {
765     return I->getKind() == IK_ListInit;
766   }
767   static ListInit *get(ArrayRef<Init *> Range, RecTy *EltTy);
768 
769   void Profile(FoldingSetNodeID &ID) const;
770 
getElement(unsigned i)771   Init *getElement(unsigned i) const {
772     assert(i < NumValues && "List element index out of range!");
773     return getTrailingObjects<Init *>()[i];
774   }
getElementType()775   RecTy *getElementType() const {
776     return cast<ListRecTy>(getType())->getElementType();
777   }
778 
779   Record *getElementAsRecord(unsigned i) const;
780 
781   Init *convertInitializerTo(RecTy *Ty) const override;
782 
783   /// This method is used by classes that refer to other
784   /// variables which may not be defined at the time they expression is formed.
785   /// If a value is set for the variable later, this method will be called on
786   /// users of the value to allow the value to propagate out.
787   ///
788   Init *resolveReferences(Resolver &R) const override;
789 
790   bool isComplete() const override;
791   bool isConcrete() const override;
792   std::string getAsString() const override;
793 
getValues()794   ArrayRef<Init*> getValues() const {
795     return ArrayRef(getTrailingObjects<Init *>(), NumValues);
796   }
797 
begin()798   const_iterator begin() const { return getTrailingObjects<Init *>(); }
end()799   const_iterator end  () const { return begin() + NumValues; }
800 
size()801   size_t         size () const { return NumValues;  }
empty()802   bool           empty() const { return NumValues == 0; }
803 
getBit(unsigned Bit)804   Init *getBit(unsigned Bit) const override {
805     llvm_unreachable("Illegal bit reference off list");
806   }
807 };
808 
809 /// Base class for operators
810 ///
811 class OpInit : public TypedInit {
812 protected:
OpInit(InitKind K,RecTy * Type,uint8_t Opc)813   explicit OpInit(InitKind K, RecTy *Type, uint8_t Opc)
814     : TypedInit(K, Type, Opc) {}
815 
816 public:
817   OpInit(const OpInit &) = delete;
818   OpInit &operator=(OpInit &) = delete;
819 
classof(const Init * I)820   static bool classof(const Init *I) {
821     return I->getKind() >= IK_FirstOpInit &&
822            I->getKind() <= IK_LastOpInit;
823   }
824 
825   // Clone - Clone this operator, replacing arguments with the new list
826   virtual OpInit *clone(ArrayRef<Init *> Operands) const = 0;
827 
828   virtual unsigned getNumOperands() const = 0;
829   virtual Init *getOperand(unsigned i) const = 0;
830 
831   Init *getBit(unsigned Bit) const override;
832 };
833 
834 /// !op (X) - Transform an init.
835 ///
836 class UnOpInit : public OpInit, public FoldingSetNode {
837 public:
838   enum UnaryOp : uint8_t {
839     TOLOWER,
840     TOUPPER,
841     CAST,
842     NOT,
843     HEAD,
844     TAIL,
845     SIZE,
846     EMPTY,
847     GETDAGOP,
848     LOG2,
849     REPR
850   };
851 
852 private:
853   Init *LHS;
854 
UnOpInit(UnaryOp opc,Init * lhs,RecTy * Type)855   UnOpInit(UnaryOp opc, Init *lhs, RecTy *Type)
856     : OpInit(IK_UnOpInit, Type, opc), LHS(lhs) {}
857 
858 public:
859   UnOpInit(const UnOpInit &) = delete;
860   UnOpInit &operator=(const UnOpInit &) = delete;
861 
classof(const Init * I)862   static bool classof(const Init *I) {
863     return I->getKind() == IK_UnOpInit;
864   }
865 
866   static UnOpInit *get(UnaryOp opc, Init *lhs, RecTy *Type);
867 
868   void Profile(FoldingSetNodeID &ID) const;
869 
870   // Clone - Clone this operator, replacing arguments with the new list
clone(ArrayRef<Init * > Operands)871   OpInit *clone(ArrayRef<Init *> Operands) const override {
872     assert(Operands.size() == 1 &&
873            "Wrong number of operands for unary operation");
874     return UnOpInit::get(getOpcode(), *Operands.begin(), getType());
875   }
876 
getNumOperands()877   unsigned getNumOperands() const override { return 1; }
878 
getOperand(unsigned i)879   Init *getOperand(unsigned i) const override {
880     assert(i == 0 && "Invalid operand id for unary operator");
881     return getOperand();
882   }
883 
getOpcode()884   UnaryOp getOpcode() const { return (UnaryOp)Opc; }
getOperand()885   Init *getOperand() const { return LHS; }
886 
887   // Fold - If possible, fold this to a simpler init.  Return this if not
888   // possible to fold.
889   Init *Fold(Record *CurRec, bool IsFinal = false) const;
890 
891   Init *resolveReferences(Resolver &R) const override;
892 
893   std::string getAsString() const override;
894 };
895 
896 /// !op (X, Y) - Combine two inits.
897 class BinOpInit : public OpInit, public FoldingSetNode {
898 public:
899   enum BinaryOp : uint8_t {
900     ADD,
901     SUB,
902     MUL,
903     DIV,
904     AND,
905     OR,
906     XOR,
907     SHL,
908     SRA,
909     SRL,
910     LISTCONCAT,
911     LISTSPLAT,
912     LISTREMOVE,
913     LISTELEM,
914     LISTSLICE,
915     RANGEC,
916     STRCONCAT,
917     INTERLEAVE,
918     CONCAT,
919     EQ,
920     NE,
921     LE,
922     LT,
923     GE,
924     GT,
925     GETDAGARG,
926     GETDAGNAME,
927     SETDAGOP,
928   };
929 
930 private:
931   Init *LHS, *RHS;
932 
BinOpInit(BinaryOp opc,Init * lhs,Init * rhs,RecTy * Type)933   BinOpInit(BinaryOp opc, Init *lhs, Init *rhs, RecTy *Type) :
934       OpInit(IK_BinOpInit, Type, opc), LHS(lhs), RHS(rhs) {}
935 
936 public:
937   BinOpInit(const BinOpInit &) = delete;
938   BinOpInit &operator=(const BinOpInit &) = delete;
939 
classof(const Init * I)940   static bool classof(const Init *I) {
941     return I->getKind() == IK_BinOpInit;
942   }
943 
944   static BinOpInit *get(BinaryOp opc, Init *lhs, Init *rhs,
945                         RecTy *Type);
946   static Init *getStrConcat(Init *lhs, Init *rhs);
947   static Init *getListConcat(TypedInit *lhs, Init *rhs);
948 
949   void Profile(FoldingSetNodeID &ID) const;
950 
951   // Clone - Clone this operator, replacing arguments with the new list
clone(ArrayRef<Init * > Operands)952   OpInit *clone(ArrayRef<Init *> Operands) const override {
953     assert(Operands.size() == 2 &&
954            "Wrong number of operands for binary operation");
955     return BinOpInit::get(getOpcode(), Operands[0], Operands[1], getType());
956   }
957 
getNumOperands()958   unsigned getNumOperands() const override { return 2; }
getOperand(unsigned i)959   Init *getOperand(unsigned i) const override {
960     switch (i) {
961     default: llvm_unreachable("Invalid operand id for binary operator");
962     case 0: return getLHS();
963     case 1: return getRHS();
964     }
965   }
966 
getOpcode()967   BinaryOp getOpcode() const { return (BinaryOp)Opc; }
getLHS()968   Init *getLHS() const { return LHS; }
getRHS()969   Init *getRHS() const { return RHS; }
970 
971   std::optional<bool> CompareInit(unsigned Opc, Init *LHS, Init *RHS) const;
972 
973   // Fold - If possible, fold this to a simpler init.  Return this if not
974   // possible to fold.
975   Init *Fold(Record *CurRec) const;
976 
977   Init *resolveReferences(Resolver &R) const override;
978 
979   std::string getAsString() const override;
980 };
981 
982 /// !op (X, Y, Z) - Combine two inits.
983 class TernOpInit : public OpInit, public FoldingSetNode {
984 public:
985   enum TernaryOp : uint8_t {
986     SUBST,
987     FOREACH,
988     FILTER,
989     IF,
990     DAG,
991     RANGE,
992     SUBSTR,
993     FIND,
994     SETDAGARG,
995     SETDAGNAME,
996   };
997 
998 private:
999   Init *LHS, *MHS, *RHS;
1000 
TernOpInit(TernaryOp opc,Init * lhs,Init * mhs,Init * rhs,RecTy * Type)1001   TernOpInit(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs,
1002              RecTy *Type) :
1003       OpInit(IK_TernOpInit, Type, opc), LHS(lhs), MHS(mhs), RHS(rhs) {}
1004 
1005 public:
1006   TernOpInit(const TernOpInit &) = delete;
1007   TernOpInit &operator=(const TernOpInit &) = delete;
1008 
classof(const Init * I)1009   static bool classof(const Init *I) {
1010     return I->getKind() == IK_TernOpInit;
1011   }
1012 
1013   static TernOpInit *get(TernaryOp opc, Init *lhs,
1014                          Init *mhs, Init *rhs,
1015                          RecTy *Type);
1016 
1017   void Profile(FoldingSetNodeID &ID) const;
1018 
1019   // Clone - Clone this operator, replacing arguments with the new list
clone(ArrayRef<Init * > Operands)1020   OpInit *clone(ArrayRef<Init *> Operands) const override {
1021     assert(Operands.size() == 3 &&
1022            "Wrong number of operands for ternary operation");
1023     return TernOpInit::get(getOpcode(), Operands[0], Operands[1], Operands[2],
1024                            getType());
1025   }
1026 
getNumOperands()1027   unsigned getNumOperands() const override { return 3; }
getOperand(unsigned i)1028   Init *getOperand(unsigned i) const override {
1029     switch (i) {
1030     default: llvm_unreachable("Invalid operand id for ternary operator");
1031     case 0: return getLHS();
1032     case 1: return getMHS();
1033     case 2: return getRHS();
1034     }
1035   }
1036 
getOpcode()1037   TernaryOp getOpcode() const { return (TernaryOp)Opc; }
getLHS()1038   Init *getLHS() const { return LHS; }
getMHS()1039   Init *getMHS() const { return MHS; }
getRHS()1040   Init *getRHS() const { return RHS; }
1041 
1042   // Fold - If possible, fold this to a simpler init.  Return this if not
1043   // possible to fold.
1044   Init *Fold(Record *CurRec) const;
1045 
isComplete()1046   bool isComplete() const override {
1047     return LHS->isComplete() && MHS->isComplete() && RHS->isComplete();
1048   }
1049 
1050   Init *resolveReferences(Resolver &R) const override;
1051 
1052   std::string getAsString() const override;
1053 };
1054 
1055 /// !cond(condition_1: value1, ... , condition_n: value)
1056 /// Selects the first value for which condition is true.
1057 /// Otherwise reports an error.
1058 class CondOpInit final : public TypedInit, public FoldingSetNode,
1059                       public TrailingObjects<CondOpInit, Init *> {
1060   unsigned NumConds;
1061   RecTy *ValType;
1062 
CondOpInit(unsigned NC,RecTy * Type)1063   CondOpInit(unsigned NC, RecTy *Type)
1064     : TypedInit(IK_CondOpInit, Type),
1065       NumConds(NC), ValType(Type) {}
1066 
numTrailingObjects(OverloadToken<Init * >)1067   size_t numTrailingObjects(OverloadToken<Init *>) const {
1068     return 2*NumConds;
1069   }
1070 
1071 public:
1072   CondOpInit(const CondOpInit &) = delete;
1073   CondOpInit &operator=(const CondOpInit &) = delete;
1074 
classof(const Init * I)1075   static bool classof(const Init *I) {
1076     return I->getKind() == IK_CondOpInit;
1077   }
1078 
1079   static CondOpInit *get(ArrayRef<Init*> C, ArrayRef<Init*> V,
1080                         RecTy *Type);
1081 
1082   void Profile(FoldingSetNodeID &ID) const;
1083 
getValType()1084   RecTy *getValType() const { return ValType; }
1085 
getNumConds()1086   unsigned getNumConds() const { return NumConds; }
1087 
getCond(unsigned Num)1088   Init *getCond(unsigned Num) const {
1089     assert(Num < NumConds && "Condition number out of range!");
1090     return getTrailingObjects<Init *>()[Num];
1091   }
1092 
getVal(unsigned Num)1093   Init *getVal(unsigned Num) const {
1094     assert(Num < NumConds && "Val number out of range!");
1095     return getTrailingObjects<Init *>()[Num+NumConds];
1096   }
1097 
getConds()1098   ArrayRef<Init *> getConds() const {
1099     return ArrayRef(getTrailingObjects<Init *>(), NumConds);
1100   }
1101 
getVals()1102   ArrayRef<Init *> getVals() const {
1103     return ArrayRef(getTrailingObjects<Init *>() + NumConds, NumConds);
1104   }
1105 
1106   Init *Fold(Record *CurRec) const;
1107 
1108   Init *resolveReferences(Resolver &R) const override;
1109 
1110   bool isConcrete() const override;
1111   bool isComplete() const override;
1112   std::string getAsString() const override;
1113 
1114   using const_case_iterator = SmallVectorImpl<Init*>::const_iterator;
1115   using const_val_iterator = SmallVectorImpl<Init*>::const_iterator;
1116 
arg_begin()1117   inline const_case_iterator  arg_begin() const { return getConds().begin(); }
arg_end()1118   inline const_case_iterator  arg_end  () const { return getConds().end(); }
1119 
case_size()1120   inline size_t              case_size () const { return NumConds; }
case_empty()1121   inline bool                case_empty() const { return NumConds == 0; }
1122 
name_begin()1123   inline const_val_iterator name_begin() const { return getVals().begin();}
name_end()1124   inline const_val_iterator name_end  () const { return getVals().end(); }
1125 
val_size()1126   inline size_t              val_size () const { return NumConds; }
val_empty()1127   inline bool                val_empty() const { return NumConds == 0; }
1128 
1129   Init *getBit(unsigned Bit) const override;
1130 };
1131 
1132 /// !foldl (a, b, expr, start, lst) - Fold over a list.
1133 class FoldOpInit : public TypedInit, public FoldingSetNode {
1134 private:
1135   Init *Start;
1136   Init *List;
1137   Init *A;
1138   Init *B;
1139   Init *Expr;
1140 
FoldOpInit(Init * Start,Init * List,Init * A,Init * B,Init * Expr,RecTy * Type)1141   FoldOpInit(Init *Start, Init *List, Init *A, Init *B, Init *Expr, RecTy *Type)
1142       : TypedInit(IK_FoldOpInit, Type), Start(Start), List(List), A(A), B(B),
1143         Expr(Expr) {}
1144 
1145 public:
1146   FoldOpInit(const FoldOpInit &) = delete;
1147   FoldOpInit &operator=(const FoldOpInit &) = delete;
1148 
classof(const Init * I)1149   static bool classof(const Init *I) { return I->getKind() == IK_FoldOpInit; }
1150 
1151   static FoldOpInit *get(Init *Start, Init *List, Init *A, Init *B, Init *Expr,
1152                          RecTy *Type);
1153 
1154   void Profile(FoldingSetNodeID &ID) const;
1155 
1156   // Fold - If possible, fold this to a simpler init.  Return this if not
1157   // possible to fold.
1158   Init *Fold(Record *CurRec) const;
1159 
isComplete()1160   bool isComplete() const override { return false; }
1161 
1162   Init *resolveReferences(Resolver &R) const override;
1163 
1164   Init *getBit(unsigned Bit) const override;
1165 
1166   std::string getAsString() const override;
1167 };
1168 
1169 /// !isa<type>(expr) - Dynamically determine the type of an expression.
1170 class IsAOpInit : public TypedInit, public FoldingSetNode {
1171 private:
1172   RecTy *CheckType;
1173   Init *Expr;
1174 
IsAOpInit(RecTy * CheckType,Init * Expr)1175   IsAOpInit(RecTy *CheckType, Init *Expr)
1176       : TypedInit(IK_IsAOpInit, IntRecTy::get(CheckType->getRecordKeeper())),
1177         CheckType(CheckType), Expr(Expr) {}
1178 
1179 public:
1180   IsAOpInit(const IsAOpInit &) = delete;
1181   IsAOpInit &operator=(const IsAOpInit &) = delete;
1182 
classof(const Init * I)1183   static bool classof(const Init *I) { return I->getKind() == IK_IsAOpInit; }
1184 
1185   static IsAOpInit *get(RecTy *CheckType, Init *Expr);
1186 
1187   void Profile(FoldingSetNodeID &ID) const;
1188 
1189   // Fold - If possible, fold this to a simpler init.  Return this if not
1190   // possible to fold.
1191   Init *Fold() const;
1192 
isComplete()1193   bool isComplete() const override { return false; }
1194 
1195   Init *resolveReferences(Resolver &R) const override;
1196 
1197   Init *getBit(unsigned Bit) const override;
1198 
1199   std::string getAsString() const override;
1200 };
1201 
1202 /// !exists<type>(expr) - Dynamically determine if a record of `type` named
1203 /// `expr` exists.
1204 class ExistsOpInit : public TypedInit, public FoldingSetNode {
1205 private:
1206   RecTy *CheckType;
1207   Init *Expr;
1208 
ExistsOpInit(RecTy * CheckType,Init * Expr)1209   ExistsOpInit(RecTy *CheckType, Init *Expr)
1210       : TypedInit(IK_ExistsOpInit, IntRecTy::get(CheckType->getRecordKeeper())),
1211         CheckType(CheckType), Expr(Expr) {}
1212 
1213 public:
1214   ExistsOpInit(const ExistsOpInit &) = delete;
1215   ExistsOpInit &operator=(const ExistsOpInit &) = delete;
1216 
classof(const Init * I)1217   static bool classof(const Init *I) { return I->getKind() == IK_ExistsOpInit; }
1218 
1219   static ExistsOpInit *get(RecTy *CheckType, Init *Expr);
1220 
1221   void Profile(FoldingSetNodeID &ID) const;
1222 
1223   // Fold - If possible, fold this to a simpler init.  Return this if not
1224   // possible to fold.
1225   Init *Fold(Record *CurRec, bool IsFinal = false) const;
1226 
isComplete()1227   bool isComplete() const override { return false; }
1228 
1229   Init *resolveReferences(Resolver &R) const override;
1230 
1231   Init *getBit(unsigned Bit) const override;
1232 
1233   std::string getAsString() const override;
1234 };
1235 
1236 /// 'Opcode' - Represent a reference to an entire variable object.
1237 class VarInit : public TypedInit {
1238   Init *VarName;
1239 
VarInit(Init * VN,RecTy * T)1240   explicit VarInit(Init *VN, RecTy *T)
1241       : TypedInit(IK_VarInit, T), VarName(VN) {}
1242 
1243 public:
1244   VarInit(const VarInit &) = delete;
1245   VarInit &operator=(const VarInit &) = delete;
1246 
classof(const Init * I)1247   static bool classof(const Init *I) {
1248     return I->getKind() == IK_VarInit;
1249   }
1250 
1251   static VarInit *get(StringRef VN, RecTy *T);
1252   static VarInit *get(Init *VN, RecTy *T);
1253 
1254   StringRef getName() const;
getNameInit()1255   Init *getNameInit() const { return VarName; }
1256 
getNameInitAsString()1257   std::string getNameInitAsString() const {
1258     return getNameInit()->getAsUnquotedString();
1259   }
1260 
1261   /// This method is used by classes that refer to other
1262   /// variables which may not be defined at the time they expression is formed.
1263   /// If a value is set for the variable later, this method will be called on
1264   /// users of the value to allow the value to propagate out.
1265   ///
1266   Init *resolveReferences(Resolver &R) const override;
1267 
1268   Init *getBit(unsigned Bit) const override;
1269 
getAsString()1270   std::string getAsString() const override { return std::string(getName()); }
1271 };
1272 
1273 /// Opcode{0} - Represent access to one bit of a variable or field.
1274 class VarBitInit final : public TypedInit {
1275   TypedInit *TI;
1276   unsigned Bit;
1277 
VarBitInit(TypedInit * T,unsigned B)1278   VarBitInit(TypedInit *T, unsigned B)
1279       : TypedInit(IK_VarBitInit, BitRecTy::get(T->getRecordKeeper())), TI(T),
1280         Bit(B) {
1281     assert(T->getType() &&
1282            (isa<IntRecTy>(T->getType()) ||
1283             (isa<BitsRecTy>(T->getType()) &&
1284              cast<BitsRecTy>(T->getType())->getNumBits() > B)) &&
1285            "Illegal VarBitInit expression!");
1286   }
1287 
1288 public:
1289   VarBitInit(const VarBitInit &) = delete;
1290   VarBitInit &operator=(const VarBitInit &) = delete;
1291 
classof(const Init * I)1292   static bool classof(const Init *I) {
1293     return I->getKind() == IK_VarBitInit;
1294   }
1295 
1296   static VarBitInit *get(TypedInit *T, unsigned B);
1297 
getBitVar()1298   Init *getBitVar() const { return TI; }
getBitNum()1299   unsigned getBitNum() const { return Bit; }
1300 
1301   std::string getAsString() const override;
1302   Init *resolveReferences(Resolver &R) const override;
1303 
getBit(unsigned B)1304   Init *getBit(unsigned B) const override {
1305     assert(B < 1 && "Bit index out of range!");
1306     return const_cast<VarBitInit*>(this);
1307   }
1308 };
1309 
1310 /// AL - Represent a reference to a 'def' in the description
1311 class DefInit : public TypedInit {
1312   friend class Record;
1313 
1314   Record *Def;
1315 
1316   explicit DefInit(Record *D);
1317 
1318 public:
1319   DefInit(const DefInit &) = delete;
1320   DefInit &operator=(const DefInit &) = delete;
1321 
classof(const Init * I)1322   static bool classof(const Init *I) {
1323     return I->getKind() == IK_DefInit;
1324   }
1325 
1326   static DefInit *get(Record*);
1327 
1328   Init *convertInitializerTo(RecTy *Ty) const override;
1329 
getDef()1330   Record *getDef() const { return Def; }
1331 
1332   //virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits);
1333 
1334   RecTy *getFieldType(StringInit *FieldName) const override;
1335 
isConcrete()1336   bool isConcrete() const override { return true; }
1337   std::string getAsString() const override;
1338 
getBit(unsigned Bit)1339   Init *getBit(unsigned Bit) const override {
1340     llvm_unreachable("Illegal bit reference off def");
1341   }
1342 };
1343 
1344 /// classname<targs...> - Represent an uninstantiated anonymous class
1345 /// instantiation.
1346 class VarDefInit final : public TypedInit,
1347                          public FoldingSetNode,
1348                          public TrailingObjects<VarDefInit, ArgumentInit *> {
1349   Record *Class;
1350   DefInit *Def = nullptr; // after instantiation
1351   unsigned NumArgs;
1352 
1353   explicit VarDefInit(Record *Class, unsigned N);
1354 
1355   DefInit *instantiate();
1356 
1357 public:
1358   VarDefInit(const VarDefInit &) = delete;
1359   VarDefInit &operator=(const VarDefInit &) = delete;
1360 
1361   // Do not use sized deallocation due to trailing objects.
delete(void * p)1362   void operator delete(void *p) { ::operator delete(p); }
1363 
classof(const Init * I)1364   static bool classof(const Init *I) {
1365     return I->getKind() == IK_VarDefInit;
1366   }
1367   static VarDefInit *get(Record *Class, ArrayRef<ArgumentInit *> Args);
1368 
1369   void Profile(FoldingSetNodeID &ID) const;
1370 
1371   Init *resolveReferences(Resolver &R) const override;
1372   Init *Fold() const;
1373 
1374   std::string getAsString() const override;
1375 
getArg(unsigned i)1376   ArgumentInit *getArg(unsigned i) const {
1377     assert(i < NumArgs && "Argument index out of range!");
1378     return getTrailingObjects<ArgumentInit *>()[i];
1379   }
1380 
1381   using const_iterator = ArgumentInit *const *;
1382 
args_begin()1383   const_iterator args_begin() const {
1384     return getTrailingObjects<ArgumentInit *>();
1385   }
args_end()1386   const_iterator args_end  () const { return args_begin() + NumArgs; }
1387 
args_size()1388   size_t         args_size () const { return NumArgs; }
args_empty()1389   bool           args_empty() const { return NumArgs == 0; }
1390 
args()1391   ArrayRef<ArgumentInit *> args() const {
1392     return ArrayRef(args_begin(), NumArgs);
1393   }
1394 
getBit(unsigned Bit)1395   Init *getBit(unsigned Bit) const override {
1396     llvm_unreachable("Illegal bit reference off anonymous def");
1397   }
1398 };
1399 
1400 /// X.Y - Represent a reference to a subfield of a variable
1401 class FieldInit : public TypedInit {
1402   Init *Rec;                // Record we are referring to
1403   StringInit *FieldName;    // Field we are accessing
1404 
FieldInit(Init * R,StringInit * FN)1405   FieldInit(Init *R, StringInit *FN)
1406       : TypedInit(IK_FieldInit, R->getFieldType(FN)), Rec(R), FieldName(FN) {
1407 #ifndef NDEBUG
1408     if (!getType()) {
1409       llvm::errs() << "In Record = " << Rec->getAsString()
1410                    << ", got FieldName = " << *FieldName
1411                    << " with non-record type!\n";
1412       llvm_unreachable("FieldInit with non-record type!");
1413     }
1414 #endif
1415   }
1416 
1417 public:
1418   FieldInit(const FieldInit &) = delete;
1419   FieldInit &operator=(const FieldInit &) = delete;
1420 
classof(const Init * I)1421   static bool classof(const Init *I) {
1422     return I->getKind() == IK_FieldInit;
1423   }
1424 
1425   static FieldInit *get(Init *R, StringInit *FN);
1426 
getRecord()1427   Init *getRecord() const { return Rec; }
getFieldName()1428   StringInit *getFieldName() const { return FieldName; }
1429 
1430   Init *getBit(unsigned Bit) const override;
1431 
1432   Init *resolveReferences(Resolver &R) const override;
1433   Init *Fold(Record *CurRec) const;
1434 
1435   bool isConcrete() const override;
getAsString()1436   std::string getAsString() const override {
1437     return Rec->getAsString() + "." + FieldName->getValue().str();
1438   }
1439 };
1440 
1441 /// (v a, b) - Represent a DAG tree value.  DAG inits are required
1442 /// to have at least one value then a (possibly empty) list of arguments.  Each
1443 /// argument can have a name associated with it.
1444 class DagInit final : public TypedInit, public FoldingSetNode,
1445                       public TrailingObjects<DagInit, Init *, StringInit *> {
1446   friend TrailingObjects;
1447 
1448   Init *Val;
1449   StringInit *ValName;
1450   unsigned NumArgs;
1451   unsigned NumArgNames;
1452 
DagInit(Init * V,StringInit * VN,unsigned NumArgs,unsigned NumArgNames)1453   DagInit(Init *V, StringInit *VN, unsigned NumArgs, unsigned NumArgNames)
1454       : TypedInit(IK_DagInit, DagRecTy::get(V->getRecordKeeper())), Val(V),
1455         ValName(VN), NumArgs(NumArgs), NumArgNames(NumArgNames) {}
1456 
numTrailingObjects(OverloadToken<Init * >)1457   size_t numTrailingObjects(OverloadToken<Init *>) const { return NumArgs; }
1458 
1459 public:
1460   DagInit(const DagInit &) = delete;
1461   DagInit &operator=(const DagInit &) = delete;
1462 
classof(const Init * I)1463   static bool classof(const Init *I) {
1464     return I->getKind() == IK_DagInit;
1465   }
1466 
1467   static DagInit *get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
1468                       ArrayRef<StringInit*> NameRange);
1469   static DagInit *get(Init *V, StringInit *VN,
1470                       ArrayRef<std::pair<Init*, StringInit*>> Args);
1471 
1472   void Profile(FoldingSetNodeID &ID) const;
1473 
getOperator()1474   Init *getOperator() const { return Val; }
1475   Record *getOperatorAsDef(ArrayRef<SMLoc> Loc) const;
1476 
getName()1477   StringInit *getName() const { return ValName; }
1478 
getNameStr()1479   StringRef getNameStr() const {
1480     return ValName ? ValName->getValue() : StringRef();
1481   }
1482 
getNumArgs()1483   unsigned getNumArgs() const { return NumArgs; }
1484 
getArg(unsigned Num)1485   Init *getArg(unsigned Num) const {
1486     assert(Num < NumArgs && "Arg number out of range!");
1487     return getTrailingObjects<Init *>()[Num];
1488   }
1489 
1490   /// This method looks up the specified argument name and returns its argument
1491   /// number or std::nullopt if that argument name does not exist.
1492   std::optional<unsigned> getArgNo(StringRef Name) const;
1493 
getArgName(unsigned Num)1494   StringInit *getArgName(unsigned Num) const {
1495     assert(Num < NumArgNames && "Arg number out of range!");
1496     return getTrailingObjects<StringInit *>()[Num];
1497   }
1498 
getArgNameStr(unsigned Num)1499   StringRef getArgNameStr(unsigned Num) const {
1500     StringInit *Init = getArgName(Num);
1501     return Init ? Init->getValue() : StringRef();
1502   }
1503 
getArgs()1504   ArrayRef<Init *> getArgs() const {
1505     return ArrayRef(getTrailingObjects<Init *>(), NumArgs);
1506   }
1507 
getArgNames()1508   ArrayRef<StringInit *> getArgNames() const {
1509     return ArrayRef(getTrailingObjects<StringInit *>(), NumArgNames);
1510   }
1511 
1512   Init *resolveReferences(Resolver &R) const override;
1513 
1514   bool isConcrete() const override;
1515   std::string getAsString() const override;
1516 
1517   using const_arg_iterator = SmallVectorImpl<Init*>::const_iterator;
1518   using const_name_iterator = SmallVectorImpl<StringInit*>::const_iterator;
1519 
arg_begin()1520   inline const_arg_iterator  arg_begin() const { return getArgs().begin(); }
arg_end()1521   inline const_arg_iterator  arg_end  () const { return getArgs().end(); }
1522 
arg_size()1523   inline size_t              arg_size () const { return NumArgs; }
arg_empty()1524   inline bool                arg_empty() const { return NumArgs == 0; }
1525 
name_begin()1526   inline const_name_iterator name_begin() const { return getArgNames().begin();}
name_end()1527   inline const_name_iterator name_end  () const { return getArgNames().end(); }
1528 
name_size()1529   inline size_t              name_size () const { return NumArgNames; }
name_empty()1530   inline bool                name_empty() const { return NumArgNames == 0; }
1531 
getBit(unsigned Bit)1532   Init *getBit(unsigned Bit) const override {
1533     llvm_unreachable("Illegal bit reference off dag");
1534   }
1535 };
1536 
1537 //===----------------------------------------------------------------------===//
1538 //  High-Level Classes
1539 //===----------------------------------------------------------------------===//
1540 
1541 /// This class represents a field in a record, including its name, type,
1542 /// value, and source location.
1543 class RecordVal {
1544   friend class Record;
1545 
1546 public:
1547   enum FieldKind {
1548     FK_Normal,        // A normal record field.
1549     FK_NonconcreteOK, // A field that can be nonconcrete ('field' keyword).
1550     FK_TemplateArg,   // A template argument.
1551   };
1552 
1553 private:
1554   Init *Name;
1555   SMLoc Loc; // Source location of definition of name.
1556   PointerIntPair<RecTy *, 2, FieldKind> TyAndKind;
1557   Init *Value;
1558   bool IsUsed = false;
1559 
1560   /// Reference locations to this record value.
1561   SmallVector<SMRange> ReferenceLocs;
1562 
1563 public:
1564   RecordVal(Init *N, RecTy *T, FieldKind K);
1565   RecordVal(Init *N, SMLoc Loc, RecTy *T, FieldKind K);
1566 
1567   /// Get the record keeper used to unique this value.
getRecordKeeper()1568   RecordKeeper &getRecordKeeper() const { return Name->getRecordKeeper(); }
1569 
1570   /// Get the name of the field as a StringRef.
1571   StringRef getName() const;
1572 
1573   /// Get the name of the field as an Init.
getNameInit()1574   Init *getNameInit() const { return Name; }
1575 
1576   /// Get the name of the field as a std::string.
getNameInitAsString()1577   std::string getNameInitAsString() const {
1578     return getNameInit()->getAsUnquotedString();
1579   }
1580 
1581   /// Get the source location of the point where the field was defined.
getLoc()1582   const SMLoc &getLoc() const { return Loc; }
1583 
1584   /// Is this a field where nonconcrete values are okay?
isNonconcreteOK()1585   bool isNonconcreteOK() const {
1586     return TyAndKind.getInt() == FK_NonconcreteOK;
1587   }
1588 
1589   /// Is this a template argument?
isTemplateArg()1590   bool isTemplateArg() const {
1591     return TyAndKind.getInt() == FK_TemplateArg;
1592   }
1593 
1594   /// Get the type of the field value as a RecTy.
getType()1595   RecTy *getType() const { return TyAndKind.getPointer(); }
1596 
1597   /// Get the type of the field for printing purposes.
1598   std::string getPrintType() const;
1599 
1600   /// Get the value of the field as an Init.
getValue()1601   Init *getValue() const { return Value; }
1602 
1603   /// Set the value of the field from an Init.
1604   bool setValue(Init *V);
1605 
1606   /// Set the value and source location of the field.
1607   bool setValue(Init *V, SMLoc NewLoc);
1608 
1609   /// Add a reference to this record value.
addReferenceLoc(SMRange Loc)1610   void addReferenceLoc(SMRange Loc) { ReferenceLocs.push_back(Loc); }
1611 
1612   /// Return the references of this record value.
getReferenceLocs()1613   ArrayRef<SMRange> getReferenceLocs() const { return ReferenceLocs; }
1614 
1615   /// Whether this value is used. Useful for reporting warnings, for example
1616   /// when a template argument is unused.
setUsed(bool Used)1617   void setUsed(bool Used) { IsUsed = Used; }
isUsed()1618   bool isUsed() const { return IsUsed; }
1619 
1620   void dump() const;
1621 
1622   /// Print the value to an output stream, possibly with a semicolon.
1623   void print(raw_ostream &OS, bool PrintSem = true) const;
1624 };
1625 
1626 inline raw_ostream &operator<<(raw_ostream &OS, const RecordVal &RV) {
1627   RV.print(OS << "  ");
1628   return OS;
1629 }
1630 
1631 class Record {
1632 public:
1633   struct AssertionInfo {
1634     SMLoc Loc;
1635     Init *Condition;
1636     Init *Message;
1637 
1638     // User-defined constructor to support std::make_unique(). It can be
1639     // removed in C++20 when braced initialization is supported.
AssertionInfoAssertionInfo1640     AssertionInfo(SMLoc Loc, Init *Condition, Init *Message)
1641         : Loc(Loc), Condition(Condition), Message(Message) {}
1642   };
1643 
1644   struct DumpInfo {
1645     SMLoc Loc;
1646     Init *Message;
1647 
1648     // User-defined constructor to support std::make_unique(). It can be
1649     // removed in C++20 when braced initialization is supported.
DumpInfoDumpInfo1650     DumpInfo(SMLoc Loc, Init *Message) : Loc(Loc), Message(Message) {}
1651   };
1652 
1653   enum RecordKind { RK_Def, RK_AnonymousDef, RK_Class, RK_MultiClass };
1654 
1655 private:
1656   Init *Name;
1657   // Location where record was instantiated, followed by the location of
1658   // multiclass prototypes used, and finally by the locations of references to
1659   // this record.
1660   SmallVector<SMLoc, 4> Locs;
1661   SmallVector<SMLoc, 0> ForwardDeclarationLocs;
1662   SmallVector<SMRange, 0> ReferenceLocs;
1663   SmallVector<Init *, 0> TemplateArgs;
1664   SmallVector<RecordVal, 0> Values;
1665   SmallVector<AssertionInfo, 0> Assertions;
1666   SmallVector<DumpInfo, 0> Dumps;
1667 
1668   // All superclasses in the inheritance forest in post-order (yes, it
1669   // must be a forest; diamond-shaped inheritance is not allowed).
1670   SmallVector<std::pair<Record *, SMRange>, 0> SuperClasses;
1671 
1672   // Tracks Record instances. Not owned by Record.
1673   RecordKeeper &TrackedRecords;
1674 
1675   // The DefInit corresponding to this record.
1676   DefInit *CorrespondingDefInit = nullptr;
1677 
1678   // Unique record ID.
1679   unsigned ID;
1680 
1681   RecordKind Kind;
1682 
1683   void checkName();
1684 
1685 public:
1686   // Constructs a record.
1687   explicit Record(Init *N, ArrayRef<SMLoc> locs, RecordKeeper &records,
1688                   RecordKind Kind = RK_Def)
Name(N)1689       : Name(N), Locs(locs.begin(), locs.end()), TrackedRecords(records),
1690         ID(getNewUID(N->getRecordKeeper())), Kind(Kind) {
1691     checkName();
1692   }
1693 
1694   explicit Record(StringRef N, ArrayRef<SMLoc> locs, RecordKeeper &records,
1695                   RecordKind Kind = RK_Def)
Record(StringInit::get (records,N),locs,records,Kind)1696       : Record(StringInit::get(records, N), locs, records, Kind) {}
1697 
1698   // When copy-constructing a Record, we must still guarantee a globally unique
1699   // ID number. Don't copy CorrespondingDefInit either, since it's owned by the
1700   // original record. All other fields can be copied normally.
Record(const Record & O)1701   Record(const Record &O)
1702       : Name(O.Name), Locs(O.Locs), TemplateArgs(O.TemplateArgs),
1703         Values(O.Values), Assertions(O.Assertions),
1704         SuperClasses(O.SuperClasses), TrackedRecords(O.TrackedRecords),
1705         ID(getNewUID(O.getRecords())), Kind(O.Kind) {}
1706 
1707   static unsigned getNewUID(RecordKeeper &RK);
1708 
getID()1709   unsigned getID() const { return ID; }
1710 
getName()1711   StringRef getName() const { return cast<StringInit>(Name)->getValue(); }
1712 
getNameInit()1713   Init *getNameInit() const {
1714     return Name;
1715   }
1716 
getNameInitAsString()1717   std::string getNameInitAsString() const {
1718     return getNameInit()->getAsUnquotedString();
1719   }
1720 
1721   void setName(Init *Name);      // Also updates RecordKeeper.
1722 
getLoc()1723   ArrayRef<SMLoc> getLoc() const { return Locs; }
appendLoc(SMLoc Loc)1724   void appendLoc(SMLoc Loc) { Locs.push_back(Loc); }
1725 
getForwardDeclarationLocs()1726   ArrayRef<SMLoc> getForwardDeclarationLocs() const {
1727     return ForwardDeclarationLocs;
1728   }
1729 
1730   /// Add a reference to this record value.
appendReferenceLoc(SMRange Loc)1731   void appendReferenceLoc(SMRange Loc) { ReferenceLocs.push_back(Loc); }
1732 
1733   /// Return the references of this record value.
getReferenceLocs()1734   ArrayRef<SMRange> getReferenceLocs() const { return ReferenceLocs; }
1735 
1736   // Update a class location when encountering a (re-)definition.
1737   void updateClassLoc(SMLoc Loc);
1738 
1739   // Make the type that this record should have based on its superclasses.
1740   RecordRecTy *getType();
1741 
1742   /// get the corresponding DefInit.
1743   DefInit *getDefInit();
1744 
isClass()1745   bool isClass() const { return Kind == RK_Class; }
1746 
isMultiClass()1747   bool isMultiClass() const { return Kind == RK_MultiClass; }
1748 
isAnonymous()1749   bool isAnonymous() const { return Kind == RK_AnonymousDef; }
1750 
getTemplateArgs()1751   ArrayRef<Init *> getTemplateArgs() const {
1752     return TemplateArgs;
1753   }
1754 
getValues()1755   ArrayRef<RecordVal> getValues() const { return Values; }
1756 
getAssertions()1757   ArrayRef<AssertionInfo> getAssertions() const { return Assertions; }
getDumps()1758   ArrayRef<DumpInfo> getDumps() const { return Dumps; }
1759 
getSuperClasses()1760   ArrayRef<std::pair<Record *, SMRange>>  getSuperClasses() const {
1761     return SuperClasses;
1762   }
1763 
1764   /// Determine whether this record has the specified direct superclass.
1765   bool hasDirectSuperClass(const Record *SuperClass) const;
1766 
1767   /// Append the direct superclasses of this record to Classes.
1768   void getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const;
1769 
isTemplateArg(Init * Name)1770   bool isTemplateArg(Init *Name) const {
1771     return llvm::is_contained(TemplateArgs, Name);
1772   }
1773 
getValue(const Init * Name)1774   const RecordVal *getValue(const Init *Name) const {
1775     for (const RecordVal &Val : Values)
1776       if (Val.Name == Name) return &Val;
1777     return nullptr;
1778   }
1779 
getValue(StringRef Name)1780   const RecordVal *getValue(StringRef Name) const {
1781     return getValue(StringInit::get(getRecords(), Name));
1782   }
1783 
getValue(const Init * Name)1784   RecordVal *getValue(const Init *Name) {
1785     return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
1786   }
1787 
getValue(StringRef Name)1788   RecordVal *getValue(StringRef Name) {
1789     return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
1790   }
1791 
addTemplateArg(Init * Name)1792   void addTemplateArg(Init *Name) {
1793     assert(!isTemplateArg(Name) && "Template arg already defined!");
1794     TemplateArgs.push_back(Name);
1795   }
1796 
addValue(const RecordVal & RV)1797   void addValue(const RecordVal &RV) {
1798     assert(getValue(RV.getNameInit()) == nullptr && "Value already added!");
1799     Values.push_back(RV);
1800   }
1801 
removeValue(Init * Name)1802   void removeValue(Init *Name) {
1803     for (unsigned i = 0, e = Values.size(); i != e; ++i)
1804       if (Values[i].getNameInit() == Name) {
1805         Values.erase(Values.begin()+i);
1806         return;
1807       }
1808     llvm_unreachable("Cannot remove an entry that does not exist!");
1809   }
1810 
removeValue(StringRef Name)1811   void removeValue(StringRef Name) {
1812     removeValue(StringInit::get(getRecords(), Name));
1813   }
1814 
addAssertion(SMLoc Loc,Init * Condition,Init * Message)1815   void addAssertion(SMLoc Loc, Init *Condition, Init *Message) {
1816     Assertions.push_back(AssertionInfo(Loc, Condition, Message));
1817   }
1818 
addDump(SMLoc Loc,Init * Message)1819   void addDump(SMLoc Loc, Init *Message) {
1820     Dumps.push_back(DumpInfo(Loc, Message));
1821   }
1822 
appendAssertions(const Record * Rec)1823   void appendAssertions(const Record *Rec) {
1824     Assertions.append(Rec->Assertions);
1825   }
1826 
appendDumps(const Record * Rec)1827   void appendDumps(const Record *Rec) { Dumps.append(Rec->Dumps); }
1828 
1829   void checkRecordAssertions();
1830   void emitRecordDumps();
1831   void checkUnusedTemplateArgs();
1832 
isSubClassOf(const Record * R)1833   bool isSubClassOf(const Record *R) const {
1834     for (const auto &SCPair : SuperClasses)
1835       if (SCPair.first == R)
1836         return true;
1837     return false;
1838   }
1839 
isSubClassOf(StringRef Name)1840   bool isSubClassOf(StringRef Name) const {
1841     for (const auto &SCPair : SuperClasses) {
1842       if (const auto *SI = dyn_cast<StringInit>(SCPair.first->getNameInit())) {
1843         if (SI->getValue() == Name)
1844           return true;
1845       } else if (SCPair.first->getNameInitAsString() == Name) {
1846         return true;
1847       }
1848     }
1849     return false;
1850   }
1851 
addSuperClass(Record * R,SMRange Range)1852   void addSuperClass(Record *R, SMRange Range) {
1853     assert(!CorrespondingDefInit &&
1854            "changing type of record after it has been referenced");
1855     assert(!isSubClassOf(R) && "Already subclassing record!");
1856     SuperClasses.push_back(std::make_pair(R, Range));
1857   }
1858 
1859   /// If there are any field references that refer to fields that have been
1860   /// filled in, we can propagate the values now.
1861   ///
1862   /// This is a final resolve: any error messages, e.g. due to undefined !cast
1863   /// references, are generated now.
1864   void resolveReferences(Init *NewName = nullptr);
1865 
1866   /// Apply the resolver to the name of the record as well as to the
1867   /// initializers of all fields of the record except SkipVal.
1868   ///
1869   /// The resolver should not resolve any of the fields itself, to avoid
1870   /// recursion / infinite loops.
1871   void resolveReferences(Resolver &R, const RecordVal *SkipVal = nullptr);
1872 
getRecords()1873   RecordKeeper &getRecords() const {
1874     return TrackedRecords;
1875   }
1876 
1877   void dump() const;
1878 
1879   //===--------------------------------------------------------------------===//
1880   // High-level methods useful to tablegen back-ends
1881   //
1882 
1883   /// Return the source location for the named field.
1884   SMLoc getFieldLoc(StringRef FieldName) const;
1885 
1886   /// Return the initializer for a value with the specified name, or throw an
1887   /// exception if the field does not exist.
1888   Init *getValueInit(StringRef FieldName) const;
1889 
1890   /// Return true if the named field is unset.
isValueUnset(StringRef FieldName)1891   bool isValueUnset(StringRef FieldName) const {
1892     return isa<UnsetInit>(getValueInit(FieldName));
1893   }
1894 
1895   /// This method looks up the specified field and returns its value as a
1896   /// string, throwing an exception if the field does not exist or if the value
1897   /// is not a string.
1898   StringRef getValueAsString(StringRef FieldName) const;
1899 
1900   /// This method looks up the specified field and returns its value as a
1901   /// string, throwing an exception if the value is not a string and
1902   /// std::nullopt if the field does not exist.
1903   std::optional<StringRef> getValueAsOptionalString(StringRef FieldName) const;
1904 
1905   /// This method looks up the specified field and returns its value as a
1906   /// BitsInit, throwing an exception if the field does not exist or if the
1907   /// value is not the right type.
1908   BitsInit *getValueAsBitsInit(StringRef FieldName) const;
1909 
1910   /// This method looks up the specified field and returns its value as a
1911   /// ListInit, throwing an exception if the field does not exist or if the
1912   /// value is not the right type.
1913   ListInit *getValueAsListInit(StringRef FieldName) const;
1914 
1915   /// This method looks up the specified field and returns its value as a
1916   /// vector of records, throwing an exception if the field does not exist or
1917   /// if the value is not the right type.
1918   std::vector<Record*> getValueAsListOfDefs(StringRef FieldName) const;
1919 
1920   /// This method looks up the specified field and returns its value as a
1921   /// vector of integers, throwing an exception if the field does not exist or
1922   /// if the value is not the right type.
1923   std::vector<int64_t> getValueAsListOfInts(StringRef FieldName) const;
1924 
1925   /// This method looks up the specified field and returns its value as a
1926   /// vector of strings, throwing an exception if the field does not exist or
1927   /// if the value is not the right type.
1928   std::vector<StringRef> getValueAsListOfStrings(StringRef FieldName) const;
1929 
1930   /// This method looks up the specified field and returns its value as a
1931   /// Record, throwing an exception if the field does not exist or if the value
1932   /// is not the right type.
1933   Record *getValueAsDef(StringRef FieldName) const;
1934 
1935   /// This method looks up the specified field and returns its value as a
1936   /// Record, returning null if the field exists but is "uninitialized" (i.e.
1937   /// set to `?`), and throwing an exception if the field does not exist or if
1938   /// its value is not the right type.
1939   Record *getValueAsOptionalDef(StringRef FieldName) const;
1940 
1941   /// This method looks up the specified field and returns its value as a bit,
1942   /// throwing an exception if the field does not exist or if the value is not
1943   /// the right type.
1944   bool getValueAsBit(StringRef FieldName) const;
1945 
1946   /// This method looks up the specified field and returns its value as a bit.
1947   /// If the field is unset, sets Unset to true and returns false.
1948   bool getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const;
1949 
1950   /// This method looks up the specified field and returns its value as an
1951   /// int64_t, throwing an exception if the field does not exist or if the
1952   /// value is not the right type.
1953   int64_t getValueAsInt(StringRef FieldName) const;
1954 
1955   /// This method looks up the specified field and returns its value as an Dag,
1956   /// throwing an exception if the field does not exist or if the value is not
1957   /// the right type.
1958   DagInit *getValueAsDag(StringRef FieldName) const;
1959 };
1960 
1961 raw_ostream &operator<<(raw_ostream &OS, const Record &R);
1962 
1963 class RecordKeeper {
1964   using RecordMap = std::map<std::string, std::unique_ptr<Record>, std::less<>>;
1965   using GlobalMap = std::map<std::string, Init *, std::less<>>;
1966 
1967 public:
1968   RecordKeeper();
1969   ~RecordKeeper();
1970 
1971   /// Return the internal implementation of the RecordKeeper.
getImpl()1972   detail::RecordKeeperImpl &getImpl() { return *Impl; }
1973 
1974   /// Get the main TableGen input file's name.
getInputFilename()1975   const std::string getInputFilename() const { return InputFilename; }
1976 
1977   /// Get the map of classes.
getClasses()1978   const RecordMap &getClasses() const { return Classes; }
1979 
1980   /// Get the map of records (defs).
getDefs()1981   const RecordMap &getDefs() const { return Defs; }
1982 
1983   /// Get the map of global variables.
getGlobals()1984   const GlobalMap &getGlobals() const { return ExtraGlobals; }
1985 
1986   /// Get the class with the specified name.
getClass(StringRef Name)1987   Record *getClass(StringRef Name) const {
1988     auto I = Classes.find(Name);
1989     return I == Classes.end() ? nullptr : I->second.get();
1990   }
1991 
1992   /// Get the concrete record with the specified name.
getDef(StringRef Name)1993   Record *getDef(StringRef Name) const {
1994     auto I = Defs.find(Name);
1995     return I == Defs.end() ? nullptr : I->second.get();
1996   }
1997 
1998   /// Get the \p Init value of the specified global variable.
getGlobal(StringRef Name)1999   Init *getGlobal(StringRef Name) const {
2000     if (Record *R = getDef(Name))
2001       return R->getDefInit();
2002     auto It = ExtraGlobals.find(Name);
2003     return It == ExtraGlobals.end() ? nullptr : It->second;
2004   }
2005 
saveInputFilename(std::string Filename)2006   void saveInputFilename(std::string Filename) {
2007     InputFilename = Filename;
2008   }
2009 
addClass(std::unique_ptr<Record> R)2010   void addClass(std::unique_ptr<Record> R) {
2011     bool Ins = Classes.insert(std::make_pair(std::string(R->getName()),
2012                                              std::move(R))).second;
2013     (void)Ins;
2014     assert(Ins && "Class already exists");
2015   }
2016 
addDef(std::unique_ptr<Record> R)2017   void addDef(std::unique_ptr<Record> R) {
2018     bool Ins = Defs.insert(std::make_pair(std::string(R->getName()),
2019                                           std::move(R))).second;
2020     (void)Ins;
2021     assert(Ins && "Record already exists");
2022   }
2023 
addExtraGlobal(StringRef Name,Init * I)2024   void addExtraGlobal(StringRef Name, Init *I) {
2025     bool Ins = ExtraGlobals.insert(std::make_pair(std::string(Name), I)).second;
2026     (void)Ins;
2027     assert(!getDef(Name));
2028     assert(Ins && "Global already exists");
2029   }
2030 
2031   Init *getNewAnonymousName();
2032 
2033   /// Start phase timing; called if the --time-phases option is specified.
startPhaseTiming()2034   void startPhaseTiming() {
2035     TimingGroup = new TimerGroup("TableGen", "TableGen Phase Timing");
2036   }
2037 
2038   /// Start timing a phase. Automatically stops any previous phase timer.
2039   void startTimer(StringRef Name);
2040 
2041   /// Stop timing a phase.
2042   void stopTimer();
2043 
2044   /// Start timing the overall backend. If the backend itself starts a timer,
2045   /// then this timer is cleared.
2046   void startBackendTimer(StringRef Name);
2047 
2048   /// Stop timing the overall backend.
2049   void stopBackendTimer();
2050 
2051   /// Stop phase timing and print the report.
stopPhaseTiming()2052   void stopPhaseTiming() {
2053     if (TimingGroup)
2054       delete TimingGroup;
2055   }
2056 
2057   //===--------------------------------------------------------------------===//
2058   // High-level helper methods, useful for tablegen backends.
2059 
2060   /// Get all the concrete records that inherit from the one specified
2061   /// class. The class must be defined.
2062   std::vector<Record *> getAllDerivedDefinitions(StringRef ClassName) const;
2063 
2064   /// Get all the concrete records that inherit from all the specified
2065   /// classes. The classes must be defined.
2066   std::vector<Record *> getAllDerivedDefinitions(
2067       ArrayRef<StringRef> ClassNames) const;
2068 
2069   /// Get all the concrete records that inherit from specified class, if the
2070   /// class is defined. Returns an empty vector if the class is not defined.
2071   std::vector<Record *>
2072   getAllDerivedDefinitionsIfDefined(StringRef ClassName) const;
2073 
2074   void dump() const;
2075 
2076 private:
2077   RecordKeeper(RecordKeeper &&) = delete;
2078   RecordKeeper(const RecordKeeper &) = delete;
2079   RecordKeeper &operator=(RecordKeeper &&) = delete;
2080   RecordKeeper &operator=(const RecordKeeper &) = delete;
2081 
2082   std::string InputFilename;
2083   RecordMap Classes, Defs;
2084   mutable StringMap<std::vector<Record *>> ClassRecordsMap;
2085   GlobalMap ExtraGlobals;
2086 
2087   // These members are for the phase timing feature. We need a timer group,
2088   // the last timer started, and a flag to say whether the last timer
2089   // is the special "backend overall timer."
2090   TimerGroup *TimingGroup = nullptr;
2091   Timer *LastTimer = nullptr;
2092   bool BackendTimer = false;
2093 
2094   /// The internal uniquer implementation of the RecordKeeper.
2095   std::unique_ptr<detail::RecordKeeperImpl> Impl;
2096 };
2097 
2098 /// Sorting predicate to sort record pointers by name.
2099 struct LessRecord {
operatorLessRecord2100   bool operator()(const Record *Rec1, const Record *Rec2) const {
2101     return Rec1->getName().compare_numeric(Rec2->getName()) < 0;
2102   }
2103 };
2104 
2105 /// Sorting predicate to sort record pointers by their
2106 /// unique ID. If you just need a deterministic order, use this, since it
2107 /// just compares two `unsigned`; the other sorting predicates require
2108 /// string manipulation.
2109 struct LessRecordByID {
operatorLessRecordByID2110   bool operator()(const Record *LHS, const Record *RHS) const {
2111     return LHS->getID() < RHS->getID();
2112   }
2113 };
2114 
2115 /// Sorting predicate to sort record pointers by their
2116 /// name field.
2117 struct LessRecordFieldName {
operatorLessRecordFieldName2118   bool operator()(const Record *Rec1, const Record *Rec2) const {
2119     return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name");
2120   }
2121 };
2122 
2123 struct LessRecordRegister {
2124   struct RecordParts {
2125     SmallVector<std::pair< bool, StringRef>, 4> Parts;
2126 
RecordPartsLessRecordRegister::RecordParts2127     RecordParts(StringRef Rec) {
2128       if (Rec.empty())
2129         return;
2130 
2131       size_t Len = 0;
2132       const char *Start = Rec.data();
2133       const char *Curr = Start;
2134       bool IsDigitPart = isDigit(Curr[0]);
2135       for (size_t I = 0, E = Rec.size(); I != E; ++I, ++Len) {
2136         bool IsDigit = isDigit(Curr[I]);
2137         if (IsDigit != IsDigitPart) {
2138           Parts.push_back(std::make_pair(IsDigitPart, StringRef(Start, Len)));
2139           Len = 0;
2140           Start = &Curr[I];
2141           IsDigitPart = isDigit(Curr[I]);
2142         }
2143       }
2144       // Push the last part.
2145       Parts.push_back(std::make_pair(IsDigitPart, StringRef(Start, Len)));
2146     }
2147 
sizeLessRecordRegister::RecordParts2148     size_t size() { return Parts.size(); }
2149 
getPartLessRecordRegister::RecordParts2150     std::pair<bool, StringRef> getPart(size_t i) {
2151       assert (i < Parts.size() && "Invalid idx!");
2152       return Parts[i];
2153     }
2154   };
2155 
operatorLessRecordRegister2156   bool operator()(const Record *Rec1, const Record *Rec2) const {
2157     int64_t LHSPositionOrder = Rec1->getValueAsInt("PositionOrder");
2158     int64_t RHSPositionOrder = Rec2->getValueAsInt("PositionOrder");
2159     if (LHSPositionOrder != RHSPositionOrder)
2160       return LHSPositionOrder < RHSPositionOrder;
2161 
2162     RecordParts LHSParts(StringRef(Rec1->getName()));
2163     RecordParts RHSParts(StringRef(Rec2->getName()));
2164 
2165     size_t LHSNumParts = LHSParts.size();
2166     size_t RHSNumParts = RHSParts.size();
2167     assert (LHSNumParts && RHSNumParts && "Expected at least one part!");
2168 
2169     if (LHSNumParts != RHSNumParts)
2170       return LHSNumParts < RHSNumParts;
2171 
2172     // We expect the registers to be of the form [_a-zA-Z]+([0-9]*[_a-zA-Z]*)*.
2173     for (size_t I = 0, E = LHSNumParts; I < E; I+=2) {
2174       std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
2175       std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
2176       // Expect even part to always be alpha.
2177       assert (LHSPart.first == false && RHSPart.first == false &&
2178               "Expected both parts to be alpha.");
2179       if (int Res = LHSPart.second.compare(RHSPart.second))
2180         return Res < 0;
2181     }
2182     for (size_t I = 1, E = LHSNumParts; I < E; I+=2) {
2183       std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
2184       std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
2185       // Expect odd part to always be numeric.
2186       assert (LHSPart.first == true && RHSPart.first == true &&
2187               "Expected both parts to be numeric.");
2188       if (LHSPart.second.size() != RHSPart.second.size())
2189         return LHSPart.second.size() < RHSPart.second.size();
2190 
2191       unsigned LHSVal, RHSVal;
2192 
2193       bool LHSFailed = LHSPart.second.getAsInteger(10, LHSVal); (void)LHSFailed;
2194       assert(!LHSFailed && "Unable to convert LHS to integer.");
2195       bool RHSFailed = RHSPart.second.getAsInteger(10, RHSVal); (void)RHSFailed;
2196       assert(!RHSFailed && "Unable to convert RHS to integer.");
2197 
2198       if (LHSVal != RHSVal)
2199         return LHSVal < RHSVal;
2200     }
2201     return LHSNumParts < RHSNumParts;
2202   }
2203 };
2204 
2205 raw_ostream &operator<<(raw_ostream &OS, const RecordKeeper &RK);
2206 
2207 //===----------------------------------------------------------------------===//
2208 //  Resolvers
2209 //===----------------------------------------------------------------------===//
2210 
2211 /// Interface for looking up the initializer for a variable name, used by
2212 /// Init::resolveReferences.
2213 class Resolver {
2214   Record *CurRec;
2215   bool IsFinal = false;
2216 
2217 public:
Resolver(Record * CurRec)2218   explicit Resolver(Record *CurRec) : CurRec(CurRec) {}
2219   virtual ~Resolver() = default;
2220 
getCurrentRecord()2221   Record *getCurrentRecord() const { return CurRec; }
2222 
2223   /// Return the initializer for the given variable name (should normally be a
2224   /// StringInit), or nullptr if the name could not be resolved.
2225   virtual Init *resolve(Init *VarName) = 0;
2226 
2227   // Whether bits in a BitsInit should stay unresolved if resolving them would
2228   // result in a ? (UnsetInit). This behavior is used to represent instruction
2229   // encodings by keeping references to unset variables within a record.
keepUnsetBits()2230   virtual bool keepUnsetBits() const { return false; }
2231 
2232   // Whether this is the final resolve step before adding a record to the
2233   // RecordKeeper. Error reporting during resolve and related constant folding
2234   // should only happen when this is true.
isFinal()2235   bool isFinal() const { return IsFinal; }
2236 
setFinal(bool Final)2237   void setFinal(bool Final) { IsFinal = Final; }
2238 };
2239 
2240 /// Resolve arbitrary mappings.
2241 class MapResolver final : public Resolver {
2242   struct MappedValue {
2243     Init *V;
2244     bool Resolved;
2245 
MappedValueMappedValue2246     MappedValue() : V(nullptr), Resolved(false) {}
MappedValueMappedValue2247     MappedValue(Init *V, bool Resolved) : V(V), Resolved(Resolved) {}
2248   };
2249 
2250   DenseMap<Init *, MappedValue> Map;
2251 
2252 public:
Resolver(CurRec)2253   explicit MapResolver(Record *CurRec = nullptr) : Resolver(CurRec) {}
2254 
set(Init * Key,Init * Value)2255   void set(Init *Key, Init *Value) { Map[Key] = {Value, false}; }
2256 
isComplete(Init * VarName)2257   bool isComplete(Init *VarName) const {
2258     auto It = Map.find(VarName);
2259     assert(It != Map.end() && "key must be present in map");
2260     return It->second.V->isComplete();
2261   }
2262 
2263   Init *resolve(Init *VarName) override;
2264 };
2265 
2266 /// Resolve all variables from a record except for unset variables.
2267 class RecordResolver final : public Resolver {
2268   DenseMap<Init *, Init *> Cache;
2269   SmallVector<Init *, 4> Stack;
2270   Init *Name = nullptr;
2271 
2272 public:
RecordResolver(Record & R)2273   explicit RecordResolver(Record &R) : Resolver(&R) {}
2274 
setName(Init * NewName)2275   void setName(Init *NewName) { Name = NewName; }
2276 
2277   Init *resolve(Init *VarName) override;
2278 
keepUnsetBits()2279   bool keepUnsetBits() const override { return true; }
2280 };
2281 
2282 /// Delegate resolving to a sub-resolver, but shadow some variable names.
2283 class ShadowResolver final : public Resolver {
2284   Resolver &R;
2285   DenseSet<Init *> Shadowed;
2286 
2287 public:
ShadowResolver(Resolver & R)2288   explicit ShadowResolver(Resolver &R)
2289       : Resolver(R.getCurrentRecord()), R(R) {
2290     setFinal(R.isFinal());
2291   }
2292 
addShadow(Init * Key)2293   void addShadow(Init *Key) { Shadowed.insert(Key); }
2294 
resolve(Init * VarName)2295   Init *resolve(Init *VarName) override {
2296     if (Shadowed.count(VarName))
2297       return nullptr;
2298     return R.resolve(VarName);
2299   }
2300 };
2301 
2302 /// (Optionally) delegate resolving to a sub-resolver, and keep track whether
2303 /// there were unresolved references.
2304 class TrackUnresolvedResolver final : public Resolver {
2305   Resolver *R;
2306   bool FoundUnresolved = false;
2307 
2308 public:
2309   explicit TrackUnresolvedResolver(Resolver *R = nullptr)
2310       : Resolver(R ? R->getCurrentRecord() : nullptr), R(R) {}
2311 
foundUnresolved()2312   bool foundUnresolved() const { return FoundUnresolved; }
2313 
2314   Init *resolve(Init *VarName) override;
2315 };
2316 
2317 /// Do not resolve anything, but keep track of whether a given variable was
2318 /// referenced.
2319 class HasReferenceResolver final : public Resolver {
2320   Init *VarNameToTrack;
2321   bool Found = false;
2322 
2323 public:
HasReferenceResolver(Init * VarNameToTrack)2324   explicit HasReferenceResolver(Init *VarNameToTrack)
2325       : Resolver(nullptr), VarNameToTrack(VarNameToTrack) {}
2326 
found()2327   bool found() const { return Found; }
2328 
2329   Init *resolve(Init *VarName) override;
2330 };
2331 
2332 void EmitDetailedRecords(RecordKeeper &RK, raw_ostream &OS);
2333 void EmitJSON(RecordKeeper &RK, raw_ostream &OS);
2334 
2335 } // end namespace llvm
2336 
2337 #endif // LLVM_TABLEGEN_RECORD_H
2338