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