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