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:
80   RecTy(RecTyKind K, RecordKeeper &RK) : Kind(K), RK(RK) {}
81   virtual ~RecTy() = default;
82 
83   RecTyKind getRecTyKind() const { return Kind; }
84 
85   /// Return the RecordKeeper that uniqued this Type.
86   RecordKeeper &getRecordKeeper() const { return RK; }
87 
88   virtual std::string getAsString() const = 0;
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 
113   BitRecTy(RecordKeeper &RK) : RecTy(BitRecTyKind, RK) {}
114 
115 public:
116   static bool classof(const RecTy *RT) {
117     return RT->getRecTyKind() == BitRecTyKind;
118   }
119 
120   static BitRecTy *get(RecordKeeper &RK);
121 
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 
131   explicit BitsRecTy(RecordKeeper &RK, unsigned Sz)
132       : RecTy(BitsRecTyKind, RK), Size(Sz) {}
133 
134 public:
135   static bool classof(const RecTy *RT) {
136     return RT->getRecTyKind() == BitsRecTyKind;
137   }
138 
139   static BitsRecTy *get(RecordKeeper &RK, unsigned Sz);
140 
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 
152   IntRecTy(RecordKeeper &RK) : RecTy(IntRecTyKind, RK) {}
153 
154 public:
155   static bool classof(const RecTy *RT) {
156     return RT->getRecTyKind() == IntRecTyKind;
157   }
158 
159   static IntRecTy *get(RecordKeeper &RK);
160 
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 
170   StringRecTy(RecordKeeper &RK) : RecTy(StringRecTyKind, RK) {}
171 
172 public:
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 
191   explicit ListRecTy(RecTy *T)
192       : RecTy(ListRecTyKind, T->getRecordKeeper()), ElementTy(T) {}
193 
194 public:
195   static bool classof(const RecTy *RT) {
196     return RT->getRecTyKind() == ListRecTyKind;
197   }
198 
199   static ListRecTy *get(RecTy *T) { return T->getListTy(); }
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 
213   DagRecTy(RecordKeeper &RK) : RecTy(DagRecTyKind, RK) {}
214 
215 public:
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 
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.
244   void operator delete(void *p) { ::operator delete(p); }
245 
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 
256   ArrayRef<Record *> getClasses() const {
257     return ArrayRef(getTrailingObjects<Record *>(), NumClasses);
258   }
259 
260   using const_record_iterator = Record * const *;
261 
262   const_record_iterator classes_begin() const { return getClasses().begin(); }
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.
336   InitKind getKind() const { return Kind; }
337 
338   /// Get the record keeper that initialized this Init.
339   RecordKeeper &getRecordKeeper() const;
340 
341 protected:
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?
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.
354   virtual bool isConcrete() const { return false; }
355 
356   /// Print this value.
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.
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.
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.
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.
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)
418       : Init(K, Opc), ValueTy(T) {}
419 
420 public:
421   TypedInit(const TypedInit &) = delete;
422   TypedInit &operator=(const TypedInit &) = delete;
423 
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.
430   RecTy *getType() const { return ValueTy; }
431 
432   /// Get the record keeper that initialized this Init.
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 
453   UnsetInit(RecordKeeper &RK) : Init(IK_UnsetInit), RK(RK) {}
454 
455 public:
456   UnsetInit(const UnsetInit &) = delete;
457   UnsetInit &operator=(const UnsetInit &) = delete;
458 
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.
467   RecordKeeper &getRecordKeeper() const { return RK; }
468 
469   Init *getCastTo(RecTy *Ty) const override;
470   Init *convertInitializerTo(RecTy *Ty) const override;
471 
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?
477   bool isComplete() const override { return false; }
478 
479   bool isConcrete() const override { return true; }
480 
481   /// Get the string representation of the Init.
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:
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 
506   static bool classof(const Init *I) { return I->getKind() == IK_ArgumentInit; }
507 
508   RecordKeeper &getRecordKeeper() const { return Value->getRecordKeeper(); }
509 
510   static ArgumentInit *get(Init *Value, ArgAuxType Aux);
511 
512   bool isPositional() const { return Aux.index() == Positional; }
513   bool isNamed() const { return Aux.index() == Named; }
514 
515   Init *getValue() const { return Value; }
516   unsigned getIndex() const {
517     assert(isPositional() && "Should be positional!");
518     return std::get<Positional>(Aux);
519   }
520   Init *getName() const {
521     assert(isNamed() && "Should be named!");
522     return std::get<Named>(Aux);
523   }
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;
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 
538   bool isComplete() const override { return false; }
539   bool isConcrete() const override { return false; }
540   Init *getBit(unsigned Bit) const override { return Value->getBit(Bit); }
541   Init *getCastTo(RecTy *Ty) const override { return Value->getCastTo(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 
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 
559   static bool classof(const Init *I) {
560     return I->getKind() == IK_BitInit;
561   }
562 
563   static BitInit *get(RecordKeeper &RK, bool V);
564 
565   bool getValue() const { return Value; }
566 
567   Init *convertInitializerTo(RecTy *Ty) const override;
568 
569   Init *getBit(unsigned Bit) const override {
570     assert(Bit < 1 && "Bit index out of range!");
571     return const_cast<BitInit*>(this);
572   }
573 
574   bool isConcrete() const override { return true; }
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 
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.
592   void operator delete(void *p) { ::operator delete(p); }
593 
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 
602   unsigned getNumBits() const { return NumBits; }
603 
604   Init *convertInitializerTo(RecTy *Ty) const override;
605   Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
606 
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 
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 
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 
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 
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 
647   int64_t getValue() const { return Value; }
648 
649   Init *convertInitializerTo(RecTy *Ty) const override;
650   Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
651 
652   bool isConcrete() const override { return true; }
653   std::string getAsString() const override;
654 
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 
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 
671   static bool classof(const Init *I) {
672     return I->getKind() == IK_AnonymousNameInit;
673   }
674 
675   static AnonymousNameInit *get(RecordKeeper &RK, unsigned);
676 
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 
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 
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 
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 
716   static StringFormat determineFormat(StringFormat Fmt1, StringFormat Fmt2) {
717     return (Fmt1 == SF_Code || Fmt2 == SF_Code) ? SF_Code : SF_String;
718   }
719 
720   StringRef getValue() const { return Value; }
721   StringFormat getFormat() const { return Format; }
722   bool hasCodeFormat() const { return Format == SF_Code; }
723 
724   Init *convertInitializerTo(RecTy *Ty) const override;
725 
726   bool isConcrete() const override { return true; }
727 
728   std::string getAsString() const override {
729     if (Format == SF_String)
730       return "\"" + Value.str() + "\"";
731     else
732       return "[{" + Value.str() + "}]";
733   }
734 
735   std::string getAsUnquotedString() const override {
736     return std::string(Value);
737   }
738 
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:
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.
762   void operator delete(void *p) { ::operator delete(p); }
763 
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 
771   Init *getElement(unsigned i) const {
772     assert(i < NumValues && "List element index out of range!");
773     return getTrailingObjects<Init *>()[i];
774   }
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 
794   ArrayRef<Init*> getValues() const {
795     return ArrayRef(getTrailingObjects<Init *>(), NumValues);
796   }
797 
798   const_iterator begin() const { return getTrailingObjects<Init *>(); }
799   const_iterator end  () const { return begin() + NumValues; }
800 
801   size_t         size () const { return NumValues;  }
802   bool           empty() const { return NumValues == 0; }
803 
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:
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 
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   };
850 
851 private:
852   Init *LHS;
853 
854   UnOpInit(UnaryOp opc, Init *lhs, RecTy *Type)
855     : OpInit(IK_UnOpInit, Type, opc), LHS(lhs) {}
856 
857 public:
858   UnOpInit(const UnOpInit &) = delete;
859   UnOpInit &operator=(const UnOpInit &) = delete;
860 
861   static bool classof(const Init *I) {
862     return I->getKind() == IK_UnOpInit;
863   }
864 
865   static UnOpInit *get(UnaryOp opc, Init *lhs, RecTy *Type);
866 
867   void Profile(FoldingSetNodeID &ID) const;
868 
869   // Clone - Clone this operator, replacing arguments with the new list
870   OpInit *clone(ArrayRef<Init *> Operands) const override {
871     assert(Operands.size() == 1 &&
872            "Wrong number of operands for unary operation");
873     return UnOpInit::get(getOpcode(), *Operands.begin(), getType());
874   }
875 
876   unsigned getNumOperands() const override { return 1; }
877 
878   Init *getOperand(unsigned i) const override {
879     assert(i == 0 && "Invalid operand id for unary operator");
880     return getOperand();
881   }
882 
883   UnaryOp getOpcode() const { return (UnaryOp)Opc; }
884   Init *getOperand() const { return LHS; }
885 
886   // Fold - If possible, fold this to a simpler init.  Return this if not
887   // possible to fold.
888   Init *Fold(Record *CurRec, bool IsFinal = false) const;
889 
890   Init *resolveReferences(Resolver &R) const override;
891 
892   std::string getAsString() const override;
893 };
894 
895 /// !op (X, Y) - Combine two inits.
896 class BinOpInit : public OpInit, public FoldingSetNode {
897 public:
898   enum BinaryOp : uint8_t {
899     ADD,
900     SUB,
901     MUL,
902     DIV,
903     AND,
904     OR,
905     XOR,
906     SHL,
907     SRA,
908     SRL,
909     LISTCONCAT,
910     LISTSPLAT,
911     LISTREMOVE,
912     LISTELEM,
913     LISTSLICE,
914     RANGE,
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 
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 
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
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 
958   unsigned getNumOperands() const override { return 2; }
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 
967   BinaryOp getOpcode() const { return (BinaryOp)Opc; }
968   Init *getLHS() const { return LHS; }
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     SUBSTR,
992     FIND,
993     SETDAGARG,
994     SETDAGNAME,
995   };
996 
997 private:
998   Init *LHS, *MHS, *RHS;
999 
1000   TernOpInit(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs,
1001              RecTy *Type) :
1002       OpInit(IK_TernOpInit, Type, opc), LHS(lhs), MHS(mhs), RHS(rhs) {}
1003 
1004 public:
1005   TernOpInit(const TernOpInit &) = delete;
1006   TernOpInit &operator=(const TernOpInit &) = delete;
1007 
1008   static bool classof(const Init *I) {
1009     return I->getKind() == IK_TernOpInit;
1010   }
1011 
1012   static TernOpInit *get(TernaryOp opc, Init *lhs,
1013                          Init *mhs, Init *rhs,
1014                          RecTy *Type);
1015 
1016   void Profile(FoldingSetNodeID &ID) const;
1017 
1018   // Clone - Clone this operator, replacing arguments with the new list
1019   OpInit *clone(ArrayRef<Init *> Operands) const override {
1020     assert(Operands.size() == 3 &&
1021            "Wrong number of operands for ternary operation");
1022     return TernOpInit::get(getOpcode(), Operands[0], Operands[1], Operands[2],
1023                            getType());
1024   }
1025 
1026   unsigned getNumOperands() const override { return 3; }
1027   Init *getOperand(unsigned i) const override {
1028     switch (i) {
1029     default: llvm_unreachable("Invalid operand id for ternary operator");
1030     case 0: return getLHS();
1031     case 1: return getMHS();
1032     case 2: return getRHS();
1033     }
1034   }
1035 
1036   TernaryOp getOpcode() const { return (TernaryOp)Opc; }
1037   Init *getLHS() const { return LHS; }
1038   Init *getMHS() const { return MHS; }
1039   Init *getRHS() const { return RHS; }
1040 
1041   // Fold - If possible, fold this to a simpler init.  Return this if not
1042   // possible to fold.
1043   Init *Fold(Record *CurRec) const;
1044 
1045   bool isComplete() const override {
1046     return LHS->isComplete() && MHS->isComplete() && RHS->isComplete();
1047   }
1048 
1049   Init *resolveReferences(Resolver &R) const override;
1050 
1051   std::string getAsString() const override;
1052 };
1053 
1054 /// !cond(condition_1: value1, ... , condition_n: value)
1055 /// Selects the first value for which condition is true.
1056 /// Otherwise reports an error.
1057 class CondOpInit final : public TypedInit, public FoldingSetNode,
1058                       public TrailingObjects<CondOpInit, Init *> {
1059   unsigned NumConds;
1060   RecTy *ValType;
1061 
1062   CondOpInit(unsigned NC, RecTy *Type)
1063     : TypedInit(IK_CondOpInit, Type),
1064       NumConds(NC), ValType(Type) {}
1065 
1066   size_t numTrailingObjects(OverloadToken<Init *>) const {
1067     return 2*NumConds;
1068   }
1069 
1070 public:
1071   CondOpInit(const CondOpInit &) = delete;
1072   CondOpInit &operator=(const CondOpInit &) = delete;
1073 
1074   static bool classof(const Init *I) {
1075     return I->getKind() == IK_CondOpInit;
1076   }
1077 
1078   static CondOpInit *get(ArrayRef<Init*> C, ArrayRef<Init*> V,
1079                         RecTy *Type);
1080 
1081   void Profile(FoldingSetNodeID &ID) const;
1082 
1083   RecTy *getValType() const { return ValType; }
1084 
1085   unsigned getNumConds() const { return NumConds; }
1086 
1087   Init *getCond(unsigned Num) const {
1088     assert(Num < NumConds && "Condition number out of range!");
1089     return getTrailingObjects<Init *>()[Num];
1090   }
1091 
1092   Init *getVal(unsigned Num) const {
1093     assert(Num < NumConds && "Val number out of range!");
1094     return getTrailingObjects<Init *>()[Num+NumConds];
1095   }
1096 
1097   ArrayRef<Init *> getConds() const {
1098     return ArrayRef(getTrailingObjects<Init *>(), NumConds);
1099   }
1100 
1101   ArrayRef<Init *> getVals() const {
1102     return ArrayRef(getTrailingObjects<Init *>() + NumConds, NumConds);
1103   }
1104 
1105   Init *Fold(Record *CurRec) const;
1106 
1107   Init *resolveReferences(Resolver &R) const override;
1108 
1109   bool isConcrete() const override;
1110   bool isComplete() const override;
1111   std::string getAsString() const override;
1112 
1113   using const_case_iterator = SmallVectorImpl<Init*>::const_iterator;
1114   using const_val_iterator = SmallVectorImpl<Init*>::const_iterator;
1115 
1116   inline const_case_iterator  arg_begin() const { return getConds().begin(); }
1117   inline const_case_iterator  arg_end  () const { return getConds().end(); }
1118 
1119   inline size_t              case_size () const { return NumConds; }
1120   inline bool                case_empty() const { return NumConds == 0; }
1121 
1122   inline const_val_iterator name_begin() const { return getVals().begin();}
1123   inline const_val_iterator name_end  () const { return getVals().end(); }
1124 
1125   inline size_t              val_size () const { return NumConds; }
1126   inline bool                val_empty() const { return NumConds == 0; }
1127 
1128   Init *getBit(unsigned Bit) const override;
1129 };
1130 
1131 /// !foldl (a, b, expr, start, lst) - Fold over a list.
1132 class FoldOpInit : public TypedInit, public FoldingSetNode {
1133 private:
1134   Init *Start;
1135   Init *List;
1136   Init *A;
1137   Init *B;
1138   Init *Expr;
1139 
1140   FoldOpInit(Init *Start, Init *List, Init *A, Init *B, Init *Expr, RecTy *Type)
1141       : TypedInit(IK_FoldOpInit, Type), Start(Start), List(List), A(A), B(B),
1142         Expr(Expr) {}
1143 
1144 public:
1145   FoldOpInit(const FoldOpInit &) = delete;
1146   FoldOpInit &operator=(const FoldOpInit &) = delete;
1147 
1148   static bool classof(const Init *I) { return I->getKind() == IK_FoldOpInit; }
1149 
1150   static FoldOpInit *get(Init *Start, Init *List, Init *A, Init *B, Init *Expr,
1151                          RecTy *Type);
1152 
1153   void Profile(FoldingSetNodeID &ID) const;
1154 
1155   // Fold - If possible, fold this to a simpler init.  Return this if not
1156   // possible to fold.
1157   Init *Fold(Record *CurRec) const;
1158 
1159   bool isComplete() const override { return false; }
1160 
1161   Init *resolveReferences(Resolver &R) const override;
1162 
1163   Init *getBit(unsigned Bit) const override;
1164 
1165   std::string getAsString() const override;
1166 };
1167 
1168 /// !isa<type>(expr) - Dynamically determine the type of an expression.
1169 class IsAOpInit : public TypedInit, public FoldingSetNode {
1170 private:
1171   RecTy *CheckType;
1172   Init *Expr;
1173 
1174   IsAOpInit(RecTy *CheckType, Init *Expr)
1175       : TypedInit(IK_IsAOpInit, IntRecTy::get(CheckType->getRecordKeeper())),
1176         CheckType(CheckType), Expr(Expr) {}
1177 
1178 public:
1179   IsAOpInit(const IsAOpInit &) = delete;
1180   IsAOpInit &operator=(const IsAOpInit &) = delete;
1181 
1182   static bool classof(const Init *I) { return I->getKind() == IK_IsAOpInit; }
1183 
1184   static IsAOpInit *get(RecTy *CheckType, Init *Expr);
1185 
1186   void Profile(FoldingSetNodeID &ID) const;
1187 
1188   // Fold - If possible, fold this to a simpler init.  Return this if not
1189   // possible to fold.
1190   Init *Fold() const;
1191 
1192   bool isComplete() const override { return false; }
1193 
1194   Init *resolveReferences(Resolver &R) const override;
1195 
1196   Init *getBit(unsigned Bit) const override;
1197 
1198   std::string getAsString() const override;
1199 };
1200 
1201 /// !exists<type>(expr) - Dynamically determine if a record of `type` named
1202 /// `expr` exists.
1203 class ExistsOpInit : public TypedInit, public FoldingSetNode {
1204 private:
1205   RecTy *CheckType;
1206   Init *Expr;
1207 
1208   ExistsOpInit(RecTy *CheckType, Init *Expr)
1209       : TypedInit(IK_ExistsOpInit, IntRecTy::get(CheckType->getRecordKeeper())),
1210         CheckType(CheckType), Expr(Expr) {}
1211 
1212 public:
1213   ExistsOpInit(const ExistsOpInit &) = delete;
1214   ExistsOpInit &operator=(const ExistsOpInit &) = delete;
1215 
1216   static bool classof(const Init *I) { return I->getKind() == IK_ExistsOpInit; }
1217 
1218   static ExistsOpInit *get(RecTy *CheckType, Init *Expr);
1219 
1220   void Profile(FoldingSetNodeID &ID) const;
1221 
1222   // Fold - If possible, fold this to a simpler init.  Return this if not
1223   // possible to fold.
1224   Init *Fold(Record *CurRec, bool IsFinal = false) const;
1225 
1226   bool isComplete() const override { return false; }
1227 
1228   Init *resolveReferences(Resolver &R) const override;
1229 
1230   Init *getBit(unsigned Bit) const override;
1231 
1232   std::string getAsString() const override;
1233 };
1234 
1235 /// 'Opcode' - Represent a reference to an entire variable object.
1236 class VarInit : public TypedInit {
1237   Init *VarName;
1238 
1239   explicit VarInit(Init *VN, RecTy *T)
1240       : TypedInit(IK_VarInit, T), VarName(VN) {}
1241 
1242 public:
1243   VarInit(const VarInit &) = delete;
1244   VarInit &operator=(const VarInit &) = delete;
1245 
1246   static bool classof(const Init *I) {
1247     return I->getKind() == IK_VarInit;
1248   }
1249 
1250   static VarInit *get(StringRef VN, RecTy *T);
1251   static VarInit *get(Init *VN, RecTy *T);
1252 
1253   StringRef getName() const;
1254   Init *getNameInit() const { return VarName; }
1255 
1256   std::string getNameInitAsString() const {
1257     return getNameInit()->getAsUnquotedString();
1258   }
1259 
1260   /// This method is used by classes that refer to other
1261   /// variables which may not be defined at the time they expression is formed.
1262   /// If a value is set for the variable later, this method will be called on
1263   /// users of the value to allow the value to propagate out.
1264   ///
1265   Init *resolveReferences(Resolver &R) const override;
1266 
1267   Init *getBit(unsigned Bit) const override;
1268 
1269   std::string getAsString() const override { return std::string(getName()); }
1270 };
1271 
1272 /// Opcode{0} - Represent access to one bit of a variable or field.
1273 class VarBitInit final : public TypedInit {
1274   TypedInit *TI;
1275   unsigned Bit;
1276 
1277   VarBitInit(TypedInit *T, unsigned B)
1278       : TypedInit(IK_VarBitInit, BitRecTy::get(T->getRecordKeeper())), TI(T),
1279         Bit(B) {
1280     assert(T->getType() &&
1281            (isa<IntRecTy>(T->getType()) ||
1282             (isa<BitsRecTy>(T->getType()) &&
1283              cast<BitsRecTy>(T->getType())->getNumBits() > B)) &&
1284            "Illegal VarBitInit expression!");
1285   }
1286 
1287 public:
1288   VarBitInit(const VarBitInit &) = delete;
1289   VarBitInit &operator=(const VarBitInit &) = delete;
1290 
1291   static bool classof(const Init *I) {
1292     return I->getKind() == IK_VarBitInit;
1293   }
1294 
1295   static VarBitInit *get(TypedInit *T, unsigned B);
1296 
1297   Init *getBitVar() const { return TI; }
1298   unsigned getBitNum() const { return Bit; }
1299 
1300   std::string getAsString() const override;
1301   Init *resolveReferences(Resolver &R) const override;
1302 
1303   Init *getBit(unsigned B) const override {
1304     assert(B < 1 && "Bit index out of range!");
1305     return const_cast<VarBitInit*>(this);
1306   }
1307 };
1308 
1309 /// AL - Represent a reference to a 'def' in the description
1310 class DefInit : public TypedInit {
1311   friend class Record;
1312 
1313   Record *Def;
1314 
1315   explicit DefInit(Record *D);
1316 
1317 public:
1318   DefInit(const DefInit &) = delete;
1319   DefInit &operator=(const DefInit &) = delete;
1320 
1321   static bool classof(const Init *I) {
1322     return I->getKind() == IK_DefInit;
1323   }
1324 
1325   static DefInit *get(Record*);
1326 
1327   Init *convertInitializerTo(RecTy *Ty) const override;
1328 
1329   Record *getDef() const { return Def; }
1330 
1331   //virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits);
1332 
1333   RecTy *getFieldType(StringInit *FieldName) const override;
1334 
1335   bool isConcrete() const override { return true; }
1336   std::string getAsString() const override;
1337 
1338   Init *getBit(unsigned Bit) const override {
1339     llvm_unreachable("Illegal bit reference off def");
1340   }
1341 };
1342 
1343 /// classname<targs...> - Represent an uninstantiated anonymous class
1344 /// instantiation.
1345 class VarDefInit final : public TypedInit,
1346                          public FoldingSetNode,
1347                          public TrailingObjects<VarDefInit, ArgumentInit *> {
1348   Record *Class;
1349   DefInit *Def = nullptr; // after instantiation
1350   unsigned NumArgs;
1351 
1352   explicit VarDefInit(Record *Class, unsigned N);
1353 
1354   DefInit *instantiate();
1355 
1356 public:
1357   VarDefInit(const VarDefInit &) = delete;
1358   VarDefInit &operator=(const VarDefInit &) = delete;
1359 
1360   // Do not use sized deallocation due to trailing objects.
1361   void operator delete(void *p) { ::operator delete(p); }
1362 
1363   static bool classof(const Init *I) {
1364     return I->getKind() == IK_VarDefInit;
1365   }
1366   static VarDefInit *get(Record *Class, ArrayRef<ArgumentInit *> Args);
1367 
1368   void Profile(FoldingSetNodeID &ID) const;
1369 
1370   Init *resolveReferences(Resolver &R) const override;
1371   Init *Fold() const;
1372 
1373   std::string getAsString() const override;
1374 
1375   ArgumentInit *getArg(unsigned i) const {
1376     assert(i < NumArgs && "Argument index out of range!");
1377     return getTrailingObjects<ArgumentInit *>()[i];
1378   }
1379 
1380   using const_iterator = ArgumentInit *const *;
1381 
1382   const_iterator args_begin() const {
1383     return getTrailingObjects<ArgumentInit *>();
1384   }
1385   const_iterator args_end  () const { return args_begin() + NumArgs; }
1386 
1387   size_t         args_size () const { return NumArgs; }
1388   bool           args_empty() const { return NumArgs == 0; }
1389 
1390   ArrayRef<ArgumentInit *> args() const {
1391     return ArrayRef(args_begin(), NumArgs);
1392   }
1393 
1394   Init *getBit(unsigned Bit) const override {
1395     llvm_unreachable("Illegal bit reference off anonymous def");
1396   }
1397 };
1398 
1399 /// X.Y - Represent a reference to a subfield of a variable
1400 class FieldInit : public TypedInit {
1401   Init *Rec;                // Record we are referring to
1402   StringInit *FieldName;    // Field we are accessing
1403 
1404   FieldInit(Init *R, StringInit *FN)
1405       : TypedInit(IK_FieldInit, R->getFieldType(FN)), Rec(R), FieldName(FN) {
1406 #ifndef NDEBUG
1407     if (!getType()) {
1408       llvm::errs() << "In Record = " << Rec->getAsString()
1409                    << ", got FieldName = " << *FieldName
1410                    << " with non-record type!\n";
1411       llvm_unreachable("FieldInit with non-record type!");
1412     }
1413 #endif
1414   }
1415 
1416 public:
1417   FieldInit(const FieldInit &) = delete;
1418   FieldInit &operator=(const FieldInit &) = delete;
1419 
1420   static bool classof(const Init *I) {
1421     return I->getKind() == IK_FieldInit;
1422   }
1423 
1424   static FieldInit *get(Init *R, StringInit *FN);
1425 
1426   Init *getRecord() const { return Rec; }
1427   StringInit *getFieldName() const { return FieldName; }
1428 
1429   Init *getBit(unsigned Bit) const override;
1430 
1431   Init *resolveReferences(Resolver &R) const override;
1432   Init *Fold(Record *CurRec) const;
1433 
1434   bool isConcrete() const override;
1435   std::string getAsString() const override {
1436     return Rec->getAsString() + "." + FieldName->getValue().str();
1437   }
1438 };
1439 
1440 /// (v a, b) - Represent a DAG tree value.  DAG inits are required
1441 /// to have at least one value then a (possibly empty) list of arguments.  Each
1442 /// argument can have a name associated with it.
1443 class DagInit final : public TypedInit, public FoldingSetNode,
1444                       public TrailingObjects<DagInit, Init *, StringInit *> {
1445   friend TrailingObjects;
1446 
1447   Init *Val;
1448   StringInit *ValName;
1449   unsigned NumArgs;
1450   unsigned NumArgNames;
1451 
1452   DagInit(Init *V, StringInit *VN, unsigned NumArgs, unsigned NumArgNames)
1453       : TypedInit(IK_DagInit, DagRecTy::get(V->getRecordKeeper())), Val(V),
1454         ValName(VN), NumArgs(NumArgs), NumArgNames(NumArgNames) {}
1455 
1456   size_t numTrailingObjects(OverloadToken<Init *>) const { return NumArgs; }
1457 
1458 public:
1459   DagInit(const DagInit &) = delete;
1460   DagInit &operator=(const DagInit &) = delete;
1461 
1462   static bool classof(const Init *I) {
1463     return I->getKind() == IK_DagInit;
1464   }
1465 
1466   static DagInit *get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
1467                       ArrayRef<StringInit*> NameRange);
1468   static DagInit *get(Init *V, StringInit *VN,
1469                       ArrayRef<std::pair<Init*, StringInit*>> Args);
1470 
1471   void Profile(FoldingSetNodeID &ID) const;
1472 
1473   Init *getOperator() const { return Val; }
1474   Record *getOperatorAsDef(ArrayRef<SMLoc> Loc) const;
1475 
1476   StringInit *getName() const { return ValName; }
1477 
1478   StringRef getNameStr() const {
1479     return ValName ? ValName->getValue() : StringRef();
1480   }
1481 
1482   unsigned getNumArgs() const { return NumArgs; }
1483 
1484   Init *getArg(unsigned Num) const {
1485     assert(Num < NumArgs && "Arg number out of range!");
1486     return getTrailingObjects<Init *>()[Num];
1487   }
1488 
1489   /// This method looks up the specified argument name and returns its argument
1490   /// number or std::nullopt if that argument name does not exist.
1491   std::optional<unsigned> getArgNo(StringRef Name) const;
1492 
1493   StringInit *getArgName(unsigned Num) const {
1494     assert(Num < NumArgNames && "Arg number out of range!");
1495     return getTrailingObjects<StringInit *>()[Num];
1496   }
1497 
1498   StringRef getArgNameStr(unsigned Num) const {
1499     StringInit *Init = getArgName(Num);
1500     return Init ? Init->getValue() : StringRef();
1501   }
1502 
1503   ArrayRef<Init *> getArgs() const {
1504     return ArrayRef(getTrailingObjects<Init *>(), NumArgs);
1505   }
1506 
1507   ArrayRef<StringInit *> getArgNames() const {
1508     return ArrayRef(getTrailingObjects<StringInit *>(), NumArgNames);
1509   }
1510 
1511   Init *resolveReferences(Resolver &R) const override;
1512 
1513   bool isConcrete() const override;
1514   std::string getAsString() const override;
1515 
1516   using const_arg_iterator = SmallVectorImpl<Init*>::const_iterator;
1517   using const_name_iterator = SmallVectorImpl<StringInit*>::const_iterator;
1518 
1519   inline const_arg_iterator  arg_begin() const { return getArgs().begin(); }
1520   inline const_arg_iterator  arg_end  () const { return getArgs().end(); }
1521 
1522   inline size_t              arg_size () const { return NumArgs; }
1523   inline bool                arg_empty() const { return NumArgs == 0; }
1524 
1525   inline const_name_iterator name_begin() const { return getArgNames().begin();}
1526   inline const_name_iterator name_end  () const { return getArgNames().end(); }
1527 
1528   inline size_t              name_size () const { return NumArgNames; }
1529   inline bool                name_empty() const { return NumArgNames == 0; }
1530 
1531   Init *getBit(unsigned Bit) const override {
1532     llvm_unreachable("Illegal bit reference off dag");
1533   }
1534 };
1535 
1536 //===----------------------------------------------------------------------===//
1537 //  High-Level Classes
1538 //===----------------------------------------------------------------------===//
1539 
1540 /// This class represents a field in a record, including its name, type,
1541 /// value, and source location.
1542 class RecordVal {
1543   friend class Record;
1544 
1545 public:
1546   enum FieldKind {
1547     FK_Normal,        // A normal record field.
1548     FK_NonconcreteOK, // A field that can be nonconcrete ('field' keyword).
1549     FK_TemplateArg,   // A template argument.
1550   };
1551 
1552 private:
1553   Init *Name;
1554   SMLoc Loc; // Source location of definition of name.
1555   PointerIntPair<RecTy *, 2, FieldKind> TyAndKind;
1556   Init *Value;
1557   bool IsUsed = false;
1558 
1559   /// Reference locations to this record value.
1560   SmallVector<SMRange> ReferenceLocs;
1561 
1562 public:
1563   RecordVal(Init *N, RecTy *T, FieldKind K);
1564   RecordVal(Init *N, SMLoc Loc, RecTy *T, FieldKind K);
1565 
1566   /// Get the record keeper used to unique this value.
1567   RecordKeeper &getRecordKeeper() const { return Name->getRecordKeeper(); }
1568 
1569   /// Get the name of the field as a StringRef.
1570   StringRef getName() const;
1571 
1572   /// Get the name of the field as an Init.
1573   Init *getNameInit() const { return Name; }
1574 
1575   /// Get the name of the field as a std::string.
1576   std::string getNameInitAsString() const {
1577     return getNameInit()->getAsUnquotedString();
1578   }
1579 
1580   /// Get the source location of the point where the field was defined.
1581   const SMLoc &getLoc() const { return Loc; }
1582 
1583   /// Is this a field where nonconcrete values are okay?
1584   bool isNonconcreteOK() const {
1585     return TyAndKind.getInt() == FK_NonconcreteOK;
1586   }
1587 
1588   /// Is this a template argument?
1589   bool isTemplateArg() const {
1590     return TyAndKind.getInt() == FK_TemplateArg;
1591   }
1592 
1593   /// Get the type of the field value as a RecTy.
1594   RecTy *getType() const { return TyAndKind.getPointer(); }
1595 
1596   /// Get the type of the field for printing purposes.
1597   std::string getPrintType() const;
1598 
1599   /// Get the value of the field as an Init.
1600   Init *getValue() const { return Value; }
1601 
1602   /// Set the value of the field from an Init.
1603   bool setValue(Init *V);
1604 
1605   /// Set the value and source location of the field.
1606   bool setValue(Init *V, SMLoc NewLoc);
1607 
1608   /// Add a reference to this record value.
1609   void addReferenceLoc(SMRange Loc) { ReferenceLocs.push_back(Loc); }
1610 
1611   /// Return the references of this record value.
1612   ArrayRef<SMRange> getReferenceLocs() const { return ReferenceLocs; }
1613 
1614   /// Whether this value is used. Useful for reporting warnings, for example
1615   /// when a template argument is unused.
1616   void setUsed(bool Used) { IsUsed = Used; }
1617   bool isUsed() const { return IsUsed; }
1618 
1619   void dump() const;
1620 
1621   /// Print the value to an output stream, possibly with a semicolon.
1622   void print(raw_ostream &OS, bool PrintSem = true) const;
1623 };
1624 
1625 inline raw_ostream &operator<<(raw_ostream &OS, const RecordVal &RV) {
1626   RV.print(OS << "  ");
1627   return OS;
1628 }
1629 
1630 class Record {
1631 public:
1632   struct AssertionInfo {
1633     SMLoc Loc;
1634     Init *Condition;
1635     Init *Message;
1636 
1637     // User-defined constructor to support std::make_unique(). It can be
1638     // removed in C++20 when braced initialization is supported.
1639     AssertionInfo(SMLoc Loc, Init *Condition, Init *Message)
1640         : Loc(Loc), Condition(Condition), Message(Message) {}
1641   };
1642 
1643 private:
1644   Init *Name;
1645   // Location where record was instantiated, followed by the location of
1646   // multiclass prototypes used, and finally by the locations of references to
1647   // this record.
1648   SmallVector<SMLoc, 4> Locs;
1649   SmallVector<SMLoc, 0> ForwardDeclarationLocs;
1650   SmallVector<SMRange, 0> ReferenceLocs;
1651   SmallVector<Init *, 0> TemplateArgs;
1652   SmallVector<RecordVal, 0> Values;
1653   SmallVector<AssertionInfo, 0> Assertions;
1654 
1655   // All superclasses in the inheritance forest in post-order (yes, it
1656   // must be a forest; diamond-shaped inheritance is not allowed).
1657   SmallVector<std::pair<Record *, SMRange>, 0> SuperClasses;
1658 
1659   // Tracks Record instances. Not owned by Record.
1660   RecordKeeper &TrackedRecords;
1661 
1662   // The DefInit corresponding to this record.
1663   DefInit *CorrespondingDefInit = nullptr;
1664 
1665   // Unique record ID.
1666   unsigned ID;
1667 
1668   bool IsAnonymous;
1669   bool IsClass;
1670 
1671   void checkName();
1672 
1673 public:
1674   // Constructs a record.
1675   explicit Record(Init *N, ArrayRef<SMLoc> locs, RecordKeeper &records,
1676                   bool Anonymous = false, bool Class = false)
1677       : Name(N), Locs(locs.begin(), locs.end()), TrackedRecords(records),
1678         ID(getNewUID(N->getRecordKeeper())), IsAnonymous(Anonymous),
1679         IsClass(Class) {
1680     checkName();
1681   }
1682 
1683   explicit Record(StringRef N, ArrayRef<SMLoc> locs, RecordKeeper &records,
1684                   bool Class = false)
1685       : Record(StringInit::get(records, N), locs, records, false, Class) {}
1686 
1687   // When copy-constructing a Record, we must still guarantee a globally unique
1688   // ID number. Don't copy CorrespondingDefInit either, since it's owned by the
1689   // original record. All other fields can be copied normally.
1690   Record(const Record &O)
1691       : Name(O.Name), Locs(O.Locs), TemplateArgs(O.TemplateArgs),
1692         Values(O.Values), Assertions(O.Assertions),
1693         SuperClasses(O.SuperClasses), TrackedRecords(O.TrackedRecords),
1694         ID(getNewUID(O.getRecords())), IsAnonymous(O.IsAnonymous),
1695         IsClass(O.IsClass) {}
1696 
1697   static unsigned getNewUID(RecordKeeper &RK);
1698 
1699   unsigned getID() const { return ID; }
1700 
1701   StringRef getName() const { return cast<StringInit>(Name)->getValue(); }
1702 
1703   Init *getNameInit() const {
1704     return Name;
1705   }
1706 
1707   std::string getNameInitAsString() const {
1708     return getNameInit()->getAsUnquotedString();
1709   }
1710 
1711   void setName(Init *Name);      // Also updates RecordKeeper.
1712 
1713   ArrayRef<SMLoc> getLoc() const { return Locs; }
1714   void appendLoc(SMLoc Loc) { Locs.push_back(Loc); }
1715 
1716   ArrayRef<SMLoc> getForwardDeclarationLocs() const {
1717     return ForwardDeclarationLocs;
1718   }
1719 
1720   /// Add a reference to this record value.
1721   void appendReferenceLoc(SMRange Loc) { ReferenceLocs.push_back(Loc); }
1722 
1723   /// Return the references of this record value.
1724   ArrayRef<SMRange> getReferenceLocs() const { return ReferenceLocs; }
1725 
1726   // Update a class location when encountering a (re-)definition.
1727   void updateClassLoc(SMLoc Loc);
1728 
1729   // Make the type that this record should have based on its superclasses.
1730   RecordRecTy *getType();
1731 
1732   /// get the corresponding DefInit.
1733   DefInit *getDefInit();
1734 
1735   bool isClass() const { return IsClass; }
1736 
1737   ArrayRef<Init *> getTemplateArgs() const {
1738     return TemplateArgs;
1739   }
1740 
1741   ArrayRef<RecordVal> getValues() const { return Values; }
1742 
1743   ArrayRef<AssertionInfo> getAssertions() const { return Assertions; }
1744 
1745   ArrayRef<std::pair<Record *, SMRange>>  getSuperClasses() const {
1746     return SuperClasses;
1747   }
1748 
1749   /// Determine whether this record has the specified direct superclass.
1750   bool hasDirectSuperClass(const Record *SuperClass) const;
1751 
1752   /// Append the direct superclasses of this record to Classes.
1753   void getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const;
1754 
1755   bool isTemplateArg(Init *Name) const {
1756     return llvm::is_contained(TemplateArgs, Name);
1757   }
1758 
1759   const RecordVal *getValue(const Init *Name) const {
1760     for (const RecordVal &Val : Values)
1761       if (Val.Name == Name) return &Val;
1762     return nullptr;
1763   }
1764 
1765   const RecordVal *getValue(StringRef Name) const {
1766     return getValue(StringInit::get(getRecords(), Name));
1767   }
1768 
1769   RecordVal *getValue(const Init *Name) {
1770     return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
1771   }
1772 
1773   RecordVal *getValue(StringRef Name) {
1774     return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
1775   }
1776 
1777   void addTemplateArg(Init *Name) {
1778     assert(!isTemplateArg(Name) && "Template arg already defined!");
1779     TemplateArgs.push_back(Name);
1780   }
1781 
1782   void addValue(const RecordVal &RV) {
1783     assert(getValue(RV.getNameInit()) == nullptr && "Value already added!");
1784     Values.push_back(RV);
1785   }
1786 
1787   void removeValue(Init *Name) {
1788     for (unsigned i = 0, e = Values.size(); i != e; ++i)
1789       if (Values[i].getNameInit() == Name) {
1790         Values.erase(Values.begin()+i);
1791         return;
1792       }
1793     llvm_unreachable("Cannot remove an entry that does not exist!");
1794   }
1795 
1796   void removeValue(StringRef Name) {
1797     removeValue(StringInit::get(getRecords(), Name));
1798   }
1799 
1800   void addAssertion(SMLoc Loc, Init *Condition, Init *Message) {
1801     Assertions.push_back(AssertionInfo(Loc, Condition, Message));
1802   }
1803 
1804   void appendAssertions(const Record *Rec) {
1805     Assertions.append(Rec->Assertions);
1806   }
1807 
1808   void checkRecordAssertions();
1809   void checkUnusedTemplateArgs();
1810 
1811   bool isSubClassOf(const Record *R) const {
1812     for (const auto &SCPair : SuperClasses)
1813       if (SCPair.first == R)
1814         return true;
1815     return false;
1816   }
1817 
1818   bool isSubClassOf(StringRef Name) const {
1819     for (const auto &SCPair : SuperClasses) {
1820       if (const auto *SI = dyn_cast<StringInit>(SCPair.first->getNameInit())) {
1821         if (SI->getValue() == Name)
1822           return true;
1823       } else if (SCPair.first->getNameInitAsString() == Name) {
1824         return true;
1825       }
1826     }
1827     return false;
1828   }
1829 
1830   void addSuperClass(Record *R, SMRange Range) {
1831     assert(!CorrespondingDefInit &&
1832            "changing type of record after it has been referenced");
1833     assert(!isSubClassOf(R) && "Already subclassing record!");
1834     SuperClasses.push_back(std::make_pair(R, Range));
1835   }
1836 
1837   /// If there are any field references that refer to fields that have been
1838   /// filled in, we can propagate the values now.
1839   ///
1840   /// This is a final resolve: any error messages, e.g. due to undefined !cast
1841   /// references, are generated now.
1842   void resolveReferences(Init *NewName = nullptr);
1843 
1844   /// Apply the resolver to the name of the record as well as to the
1845   /// initializers of all fields of the record except SkipVal.
1846   ///
1847   /// The resolver should not resolve any of the fields itself, to avoid
1848   /// recursion / infinite loops.
1849   void resolveReferences(Resolver &R, const RecordVal *SkipVal = nullptr);
1850 
1851   RecordKeeper &getRecords() const {
1852     return TrackedRecords;
1853   }
1854 
1855   bool isAnonymous() const {
1856     return IsAnonymous;
1857   }
1858 
1859   void dump() const;
1860 
1861   //===--------------------------------------------------------------------===//
1862   // High-level methods useful to tablegen back-ends
1863   //
1864 
1865   /// Return the source location for the named field.
1866   SMLoc getFieldLoc(StringRef FieldName) const;
1867 
1868   /// Return the initializer for a value with the specified name, or throw an
1869   /// exception if the field does not exist.
1870   Init *getValueInit(StringRef FieldName) const;
1871 
1872   /// Return true if the named field is unset.
1873   bool isValueUnset(StringRef FieldName) const {
1874     return isa<UnsetInit>(getValueInit(FieldName));
1875   }
1876 
1877   /// This method looks up the specified field and returns its value as a
1878   /// string, throwing an exception if the field does not exist or if the value
1879   /// is not a string.
1880   StringRef getValueAsString(StringRef FieldName) const;
1881 
1882   /// This method looks up the specified field and returns its value as a
1883   /// string, throwing an exception if the value is not a string and
1884   /// std::nullopt if the field does not exist.
1885   std::optional<StringRef> getValueAsOptionalString(StringRef FieldName) const;
1886 
1887   /// This method looks up the specified field and returns its value as a
1888   /// BitsInit, throwing an exception if the field does not exist or if the
1889   /// value is not the right type.
1890   BitsInit *getValueAsBitsInit(StringRef FieldName) const;
1891 
1892   /// This method looks up the specified field and returns its value as a
1893   /// ListInit, throwing an exception if the field does not exist or if the
1894   /// value is not the right type.
1895   ListInit *getValueAsListInit(StringRef FieldName) const;
1896 
1897   /// This method looks up the specified field and returns its value as a
1898   /// vector of records, throwing an exception if the field does not exist or
1899   /// if the value is not the right type.
1900   std::vector<Record*> getValueAsListOfDefs(StringRef FieldName) const;
1901 
1902   /// This method looks up the specified field and returns its value as a
1903   /// vector of integers, throwing an exception if the field does not exist or
1904   /// if the value is not the right type.
1905   std::vector<int64_t> getValueAsListOfInts(StringRef FieldName) const;
1906 
1907   /// This method looks up the specified field and returns its value as a
1908   /// vector of strings, throwing an exception if the field does not exist or
1909   /// if the value is not the right type.
1910   std::vector<StringRef> getValueAsListOfStrings(StringRef FieldName) const;
1911 
1912   /// This method looks up the specified field and returns its value as a
1913   /// Record, throwing an exception if the field does not exist or if the value
1914   /// is not the right type.
1915   Record *getValueAsDef(StringRef FieldName) const;
1916 
1917   /// This method looks up the specified field and returns its value as a
1918   /// Record, returning null if the field exists but is "uninitialized" (i.e.
1919   /// set to `?`), and throwing an exception if the field does not exist or if
1920   /// its value is not the right type.
1921   Record *getValueAsOptionalDef(StringRef FieldName) const;
1922 
1923   /// This method looks up the specified field and returns its value as a bit,
1924   /// throwing an exception if the field does not exist or if the value is not
1925   /// the right type.
1926   bool getValueAsBit(StringRef FieldName) const;
1927 
1928   /// This method looks up the specified field and returns its value as a bit.
1929   /// If the field is unset, sets Unset to true and returns false.
1930   bool getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const;
1931 
1932   /// This method looks up the specified field and returns its value as an
1933   /// int64_t, throwing an exception if the field does not exist or if the
1934   /// value is not the right type.
1935   int64_t getValueAsInt(StringRef FieldName) const;
1936 
1937   /// This method looks up the specified field and returns its value as an Dag,
1938   /// throwing an exception if the field does not exist or if the value is not
1939   /// the right type.
1940   DagInit *getValueAsDag(StringRef FieldName) const;
1941 };
1942 
1943 raw_ostream &operator<<(raw_ostream &OS, const Record &R);
1944 
1945 class RecordKeeper {
1946   using RecordMap = std::map<std::string, std::unique_ptr<Record>, std::less<>>;
1947   using GlobalMap = std::map<std::string, Init *, std::less<>>;
1948 
1949 public:
1950   RecordKeeper();
1951   ~RecordKeeper();
1952 
1953   /// Return the internal implementation of the RecordKeeper.
1954   detail::RecordKeeperImpl &getImpl() { return *Impl; }
1955 
1956   /// Get the main TableGen input file's name.
1957   const std::string getInputFilename() const { return InputFilename; }
1958 
1959   /// Get the map of classes.
1960   const RecordMap &getClasses() const { return Classes; }
1961 
1962   /// Get the map of records (defs).
1963   const RecordMap &getDefs() const { return Defs; }
1964 
1965   /// Get the map of global variables.
1966   const GlobalMap &getGlobals() const { return ExtraGlobals; }
1967 
1968   /// Get the class with the specified name.
1969   Record *getClass(StringRef Name) const {
1970     auto I = Classes.find(Name);
1971     return I == Classes.end() ? nullptr : I->second.get();
1972   }
1973 
1974   /// Get the concrete record with the specified name.
1975   Record *getDef(StringRef Name) const {
1976     auto I = Defs.find(Name);
1977     return I == Defs.end() ? nullptr : I->second.get();
1978   }
1979 
1980   /// Get the \p Init value of the specified global variable.
1981   Init *getGlobal(StringRef Name) const {
1982     if (Record *R = getDef(Name))
1983       return R->getDefInit();
1984     auto It = ExtraGlobals.find(Name);
1985     return It == ExtraGlobals.end() ? nullptr : It->second;
1986   }
1987 
1988   void saveInputFilename(std::string Filename) {
1989     InputFilename = Filename;
1990   }
1991 
1992   void addClass(std::unique_ptr<Record> R) {
1993     bool Ins = Classes.insert(std::make_pair(std::string(R->getName()),
1994                                              std::move(R))).second;
1995     (void)Ins;
1996     assert(Ins && "Class already exists");
1997   }
1998 
1999   void addDef(std::unique_ptr<Record> R) {
2000     bool Ins = Defs.insert(std::make_pair(std::string(R->getName()),
2001                                           std::move(R))).second;
2002     (void)Ins;
2003     assert(Ins && "Record already exists");
2004   }
2005 
2006   void addExtraGlobal(StringRef Name, Init *I) {
2007     bool Ins = ExtraGlobals.insert(std::make_pair(std::string(Name), I)).second;
2008     (void)Ins;
2009     assert(!getDef(Name));
2010     assert(Ins && "Global already exists");
2011   }
2012 
2013   Init *getNewAnonymousName();
2014 
2015   /// Start phase timing; called if the --time-phases option is specified.
2016   void startPhaseTiming() {
2017     TimingGroup = new TimerGroup("TableGen", "TableGen Phase Timing");
2018   }
2019 
2020   /// Start timing a phase. Automatically stops any previous phase timer.
2021   void startTimer(StringRef Name);
2022 
2023   /// Stop timing a phase.
2024   void stopTimer();
2025 
2026   /// Start timing the overall backend. If the backend itself starts a timer,
2027   /// then this timer is cleared.
2028   void startBackendTimer(StringRef Name);
2029 
2030   /// Stop timing the overall backend.
2031   void stopBackendTimer();
2032 
2033   /// Stop phase timing and print the report.
2034   void stopPhaseTiming() {
2035     if (TimingGroup)
2036       delete TimingGroup;
2037   }
2038 
2039   //===--------------------------------------------------------------------===//
2040   // High-level helper methods, useful for tablegen backends.
2041 
2042   /// Get all the concrete records that inherit from the one specified
2043   /// class. The class must be defined.
2044   std::vector<Record *> getAllDerivedDefinitions(StringRef ClassName) const;
2045 
2046   /// Get all the concrete records that inherit from all the specified
2047   /// classes. The classes must be defined.
2048   std::vector<Record *> getAllDerivedDefinitions(
2049       ArrayRef<StringRef> ClassNames) const;
2050 
2051   /// Get all the concrete records that inherit from specified class, if the
2052   /// class is defined. Returns an empty vector if the class is not defined.
2053   std::vector<Record *>
2054   getAllDerivedDefinitionsIfDefined(StringRef ClassName) const;
2055 
2056   void dump() const;
2057 
2058 private:
2059   RecordKeeper(RecordKeeper &&) = delete;
2060   RecordKeeper(const RecordKeeper &) = delete;
2061   RecordKeeper &operator=(RecordKeeper &&) = delete;
2062   RecordKeeper &operator=(const RecordKeeper &) = delete;
2063 
2064   std::string InputFilename;
2065   RecordMap Classes, Defs;
2066   mutable StringMap<std::vector<Record *>> ClassRecordsMap;
2067   GlobalMap ExtraGlobals;
2068 
2069   // These members are for the phase timing feature. We need a timer group,
2070   // the last timer started, and a flag to say whether the last timer
2071   // is the special "backend overall timer."
2072   TimerGroup *TimingGroup = nullptr;
2073   Timer *LastTimer = nullptr;
2074   bool BackendTimer = false;
2075 
2076   /// The internal uniquer implementation of the RecordKeeper.
2077   std::unique_ptr<detail::RecordKeeperImpl> Impl;
2078 };
2079 
2080 /// Sorting predicate to sort record pointers by name.
2081 struct LessRecord {
2082   bool operator()(const Record *Rec1, const Record *Rec2) const {
2083     return StringRef(Rec1->getName()).compare_numeric(Rec2->getName()) < 0;
2084   }
2085 };
2086 
2087 /// Sorting predicate to sort record pointers by their
2088 /// unique ID. If you just need a deterministic order, use this, since it
2089 /// just compares two `unsigned`; the other sorting predicates require
2090 /// string manipulation.
2091 struct LessRecordByID {
2092   bool operator()(const Record *LHS, const Record *RHS) const {
2093     return LHS->getID() < RHS->getID();
2094   }
2095 };
2096 
2097 /// Sorting predicate to sort record pointers by their
2098 /// name field.
2099 struct LessRecordFieldName {
2100   bool operator()(const Record *Rec1, const Record *Rec2) const {
2101     return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name");
2102   }
2103 };
2104 
2105 struct LessRecordRegister {
2106   struct RecordParts {
2107     SmallVector<std::pair< bool, StringRef>, 4> Parts;
2108 
2109     RecordParts(StringRef Rec) {
2110       if (Rec.empty())
2111         return;
2112 
2113       size_t Len = 0;
2114       const char *Start = Rec.data();
2115       const char *Curr = Start;
2116       bool IsDigitPart = isDigit(Curr[0]);
2117       for (size_t I = 0, E = Rec.size(); I != E; ++I, ++Len) {
2118         bool IsDigit = isDigit(Curr[I]);
2119         if (IsDigit != IsDigitPart) {
2120           Parts.push_back(std::make_pair(IsDigitPart, StringRef(Start, Len)));
2121           Len = 0;
2122           Start = &Curr[I];
2123           IsDigitPart = isDigit(Curr[I]);
2124         }
2125       }
2126       // Push the last part.
2127       Parts.push_back(std::make_pair(IsDigitPart, StringRef(Start, Len)));
2128     }
2129 
2130     size_t size() { return Parts.size(); }
2131 
2132     std::pair<bool, StringRef> getPart(size_t i) {
2133       assert (i < Parts.size() && "Invalid idx!");
2134       return Parts[i];
2135     }
2136   };
2137 
2138   bool operator()(const Record *Rec1, const Record *Rec2) const {
2139     RecordParts LHSParts(StringRef(Rec1->getName()));
2140     RecordParts RHSParts(StringRef(Rec2->getName()));
2141 
2142     size_t LHSNumParts = LHSParts.size();
2143     size_t RHSNumParts = RHSParts.size();
2144     assert (LHSNumParts && RHSNumParts && "Expected at least one part!");
2145 
2146     if (LHSNumParts != RHSNumParts)
2147       return LHSNumParts < RHSNumParts;
2148 
2149     // We expect the registers to be of the form [_a-zA-Z]+([0-9]*[_a-zA-Z]*)*.
2150     for (size_t I = 0, E = LHSNumParts; I < E; I+=2) {
2151       std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
2152       std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
2153       // Expect even part to always be alpha.
2154       assert (LHSPart.first == false && RHSPart.first == false &&
2155               "Expected both parts to be alpha.");
2156       if (int Res = LHSPart.second.compare(RHSPart.second))
2157         return Res < 0;
2158     }
2159     for (size_t I = 1, E = LHSNumParts; I < E; I+=2) {
2160       std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
2161       std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
2162       // Expect odd part to always be numeric.
2163       assert (LHSPart.first == true && RHSPart.first == true &&
2164               "Expected both parts to be numeric.");
2165       if (LHSPart.second.size() != RHSPart.second.size())
2166         return LHSPart.second.size() < RHSPart.second.size();
2167 
2168       unsigned LHSVal, RHSVal;
2169 
2170       bool LHSFailed = LHSPart.second.getAsInteger(10, LHSVal); (void)LHSFailed;
2171       assert(!LHSFailed && "Unable to convert LHS to integer.");
2172       bool RHSFailed = RHSPart.second.getAsInteger(10, RHSVal); (void)RHSFailed;
2173       assert(!RHSFailed && "Unable to convert RHS to integer.");
2174 
2175       if (LHSVal != RHSVal)
2176         return LHSVal < RHSVal;
2177     }
2178     return LHSNumParts < RHSNumParts;
2179   }
2180 };
2181 
2182 raw_ostream &operator<<(raw_ostream &OS, const RecordKeeper &RK);
2183 
2184 //===----------------------------------------------------------------------===//
2185 //  Resolvers
2186 //===----------------------------------------------------------------------===//
2187 
2188 /// Interface for looking up the initializer for a variable name, used by
2189 /// Init::resolveReferences.
2190 class Resolver {
2191   Record *CurRec;
2192   bool IsFinal = false;
2193 
2194 public:
2195   explicit Resolver(Record *CurRec) : CurRec(CurRec) {}
2196   virtual ~Resolver() = default;
2197 
2198   Record *getCurrentRecord() const { return CurRec; }
2199 
2200   /// Return the initializer for the given variable name (should normally be a
2201   /// StringInit), or nullptr if the name could not be resolved.
2202   virtual Init *resolve(Init *VarName) = 0;
2203 
2204   // Whether bits in a BitsInit should stay unresolved if resolving them would
2205   // result in a ? (UnsetInit). This behavior is used to represent instruction
2206   // encodings by keeping references to unset variables within a record.
2207   virtual bool keepUnsetBits() const { return false; }
2208 
2209   // Whether this is the final resolve step before adding a record to the
2210   // RecordKeeper. Error reporting during resolve and related constant folding
2211   // should only happen when this is true.
2212   bool isFinal() const { return IsFinal; }
2213 
2214   void setFinal(bool Final) { IsFinal = Final; }
2215 };
2216 
2217 /// Resolve arbitrary mappings.
2218 class MapResolver final : public Resolver {
2219   struct MappedValue {
2220     Init *V;
2221     bool Resolved;
2222 
2223     MappedValue() : V(nullptr), Resolved(false) {}
2224     MappedValue(Init *V, bool Resolved) : V(V), Resolved(Resolved) {}
2225   };
2226 
2227   DenseMap<Init *, MappedValue> Map;
2228 
2229 public:
2230   explicit MapResolver(Record *CurRec = nullptr) : Resolver(CurRec) {}
2231 
2232   void set(Init *Key, Init *Value) { Map[Key] = {Value, false}; }
2233 
2234   bool isComplete(Init *VarName) const {
2235     auto It = Map.find(VarName);
2236     assert(It != Map.end() && "key must be present in map");
2237     return It->second.V->isComplete();
2238   }
2239 
2240   Init *resolve(Init *VarName) override;
2241 };
2242 
2243 /// Resolve all variables from a record except for unset variables.
2244 class RecordResolver final : public Resolver {
2245   DenseMap<Init *, Init *> Cache;
2246   SmallVector<Init *, 4> Stack;
2247   Init *Name = nullptr;
2248 
2249 public:
2250   explicit RecordResolver(Record &R) : Resolver(&R) {}
2251 
2252   void setName(Init *NewName) { Name = NewName; }
2253 
2254   Init *resolve(Init *VarName) override;
2255 
2256   bool keepUnsetBits() const override { return true; }
2257 };
2258 
2259 /// Delegate resolving to a sub-resolver, but shadow some variable names.
2260 class ShadowResolver final : public Resolver {
2261   Resolver &R;
2262   DenseSet<Init *> Shadowed;
2263 
2264 public:
2265   explicit ShadowResolver(Resolver &R)
2266       : Resolver(R.getCurrentRecord()), R(R) {
2267     setFinal(R.isFinal());
2268   }
2269 
2270   void addShadow(Init *Key) { Shadowed.insert(Key); }
2271 
2272   Init *resolve(Init *VarName) override {
2273     if (Shadowed.count(VarName))
2274       return nullptr;
2275     return R.resolve(VarName);
2276   }
2277 };
2278 
2279 /// (Optionally) delegate resolving to a sub-resolver, and keep track whether
2280 /// there were unresolved references.
2281 class TrackUnresolvedResolver final : public Resolver {
2282   Resolver *R;
2283   bool FoundUnresolved = false;
2284 
2285 public:
2286   explicit TrackUnresolvedResolver(Resolver *R = nullptr)
2287       : Resolver(R ? R->getCurrentRecord() : nullptr), R(R) {}
2288 
2289   bool foundUnresolved() const { return FoundUnresolved; }
2290 
2291   Init *resolve(Init *VarName) override;
2292 };
2293 
2294 /// Do not resolve anything, but keep track of whether a given variable was
2295 /// referenced.
2296 class HasReferenceResolver final : public Resolver {
2297   Init *VarNameToTrack;
2298   bool Found = false;
2299 
2300 public:
2301   explicit HasReferenceResolver(Init *VarNameToTrack)
2302       : Resolver(nullptr), VarNameToTrack(VarNameToTrack) {}
2303 
2304   bool found() const { return Found; }
2305 
2306   Init *resolve(Init *VarName) override;
2307 };
2308 
2309 void EmitDetailedRecords(RecordKeeper &RK, raw_ostream &OS);
2310 void EmitJSON(RecordKeeper &RK, raw_ostream &OS);
2311 
2312 } // end namespace llvm
2313 
2314 #endif // LLVM_TABLEGEN_RECORD_H
2315