]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/TableGen/Record.h
Merge ^/head r312309 through r312623.
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / TableGen / Record.h
1 //===- llvm/TableGen/Record.h - Classes for Table Records -------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the main TableGen data structures, including the TableGen
11 // types, values, and high-level data structures.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_TABLEGEN_RECORD_H
16 #define LLVM_TABLEGEN_RECORD_H
17
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/FoldingSet.h"
20 #include "llvm/ADT/PointerIntPair.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/Support/Casting.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/SMLoc.h"
26 #include "llvm/Support/TrailingObjects.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <algorithm>
29 #include <cassert>
30 #include <cstddef>
31 #include <cstdint>
32 #include <map>
33 #include <memory>
34 #include <string>
35 #include <utility>
36 #include <vector>
37
38 namespace llvm {
39
40 class ListRecTy;
41 class Record;
42 class RecordKeeper;
43 class RecordVal;
44 class StringInit;
45 struct MultiClass;
46
47 //===----------------------------------------------------------------------===//
48 //  Type Classes
49 //===----------------------------------------------------------------------===//
50
51 class RecTy {
52 public:
53   /// \brief Subclass discriminator (for dyn_cast<> et al.)
54   enum RecTyKind {
55     BitRecTyKind,
56     BitsRecTyKind,
57     CodeRecTyKind,
58     IntRecTyKind,
59     StringRecTyKind,
60     ListRecTyKind,
61     DagRecTyKind,
62     RecordRecTyKind
63   };
64
65 private:
66   RecTyKind Kind;
67   ListRecTy *ListTy = nullptr;
68
69 public:
70   RecTy(RecTyKind K) : Kind(K) {}
71   virtual ~RecTy() = default;
72
73   RecTyKind getRecTyKind() const { return Kind; }
74
75   virtual std::string getAsString() const = 0;
76   void print(raw_ostream &OS) const { OS << getAsString(); }
77   void dump() const;
78
79   /// Return true if all values of 'this' type can be converted to the specified
80   /// type.
81   virtual bool typeIsConvertibleTo(const RecTy *RHS) const;
82
83   /// Returns the type representing list<this>.
84   ListRecTy *getListTy();
85 };
86
87 inline raw_ostream &operator<<(raw_ostream &OS, const RecTy &Ty) {
88   Ty.print(OS);
89   return OS;
90 }
91
92 /// 'bit' - Represent a single bit
93 ///
94 class BitRecTy : public RecTy {
95   static BitRecTy Shared;
96
97   BitRecTy() : RecTy(BitRecTyKind) {}
98
99 public:
100   static bool classof(const RecTy *RT) {
101     return RT->getRecTyKind() == BitRecTyKind;
102   }
103
104   static BitRecTy *get() { return &Shared; }
105
106   std::string getAsString() const override { return "bit"; }
107
108   bool typeIsConvertibleTo(const RecTy *RHS) const override;
109 };
110
111 /// 'bits<n>' - Represent a fixed number of bits
112 ///
113 class BitsRecTy : public RecTy {
114   unsigned Size;
115
116   explicit BitsRecTy(unsigned Sz) : RecTy(BitsRecTyKind), Size(Sz) {}
117
118 public:
119   static bool classof(const RecTy *RT) {
120     return RT->getRecTyKind() == BitsRecTyKind;
121   }
122
123   static BitsRecTy *get(unsigned Sz);
124
125   unsigned getNumBits() const { return Size; }
126
127   std::string getAsString() const override;
128
129   bool typeIsConvertibleTo(const RecTy *RHS) const override;
130 };
131
132 /// 'code' - Represent a code fragment
133 ///
134 class CodeRecTy : public RecTy {
135   static CodeRecTy Shared;
136
137   CodeRecTy() : RecTy(CodeRecTyKind) {}
138
139 public:
140   static bool classof(const RecTy *RT) {
141     return RT->getRecTyKind() == CodeRecTyKind;
142   }
143
144   static CodeRecTy *get() { return &Shared; }
145
146   std::string getAsString() const override { return "code"; }
147 };
148
149 /// 'int' - Represent an integer value of no particular size
150 ///
151 class IntRecTy : public RecTy {
152   static IntRecTy Shared;
153
154   IntRecTy() : RecTy(IntRecTyKind) {}
155
156 public:
157   static bool classof(const RecTy *RT) {
158     return RT->getRecTyKind() == IntRecTyKind;
159   }
160
161   static IntRecTy *get() { return &Shared; }
162
163   std::string getAsString() const override { return "int"; }
164
165   bool typeIsConvertibleTo(const RecTy *RHS) const override;
166 };
167
168 /// 'string' - Represent an string value
169 ///
170 class StringRecTy : public RecTy {
171   static StringRecTy Shared;
172
173   StringRecTy() : RecTy(StringRecTyKind) {}
174
175 public:
176   static bool classof(const RecTy *RT) {
177     return RT->getRecTyKind() == StringRecTyKind ||
178            RT->getRecTyKind() == CodeRecTyKind;
179   }
180
181   static StringRecTy *get() { return &Shared; }
182
183   std::string getAsString() const override;
184 };
185
186 /// 'list<Ty>' - Represent a list of values, all of which must be of
187 /// the specified type.
188 ///
189 class ListRecTy : public RecTy {
190   RecTy *Ty;
191
192   explicit ListRecTy(RecTy *T) : RecTy(ListRecTyKind), Ty(T) {}
193
194   friend ListRecTy *RecTy::getListTy();
195
196 public:
197   static bool classof(const RecTy *RT) {
198     return RT->getRecTyKind() == ListRecTyKind;
199   }
200
201   static ListRecTy *get(RecTy *T) { return T->getListTy(); }
202   RecTy *getElementType() const { return Ty; }
203
204   std::string getAsString() const override;
205
206   bool typeIsConvertibleTo(const RecTy *RHS) const override;
207 };
208
209 /// 'dag' - Represent a dag fragment
210 ///
211 class DagRecTy : public RecTy {
212   static DagRecTy Shared;
213
214   DagRecTy() : RecTy(DagRecTyKind) {}
215
216 public:
217   static bool classof(const RecTy *RT) {
218     return RT->getRecTyKind() == DagRecTyKind;
219   }
220
221   static DagRecTy *get() { return &Shared; }
222
223   std::string getAsString() const override;
224 };
225
226 /// '[classname]' - Represent an instance of a class, such as:
227 /// (R32 X = EAX).
228 ///
229 class RecordRecTy : public RecTy {
230   Record *Rec;
231
232   explicit RecordRecTy(Record *R) : RecTy(RecordRecTyKind), Rec(R) {}
233
234   friend class Record;
235
236 public:
237   static bool classof(const RecTy *RT) {
238     return RT->getRecTyKind() == RecordRecTyKind;
239   }
240
241   static RecordRecTy *get(Record *R);
242
243   Record *getRecord() const { return Rec; }
244
245   std::string getAsString() const override;
246
247   bool typeIsConvertibleTo(const RecTy *RHS) const override;
248 };
249
250 /// Find a common type that T1 and T2 convert to.
251 /// Return 0 if no such type exists.
252 ///
253 RecTy *resolveTypes(RecTy *T1, RecTy *T2);
254
255 //===----------------------------------------------------------------------===//
256 //  Initializer Classes
257 //===----------------------------------------------------------------------===//
258
259 class Init {
260 protected:
261   /// \brief Discriminator enum (for isa<>, dyn_cast<>, et al.)
262   ///
263   /// This enum is laid out by a preorder traversal of the inheritance
264   /// hierarchy, and does not contain an entry for abstract classes, as per
265   /// the recommendation in docs/HowToSetUpLLVMStyleRTTI.rst.
266   ///
267   /// We also explicitly include "first" and "last" values for each
268   /// interior node of the inheritance tree, to make it easier to read the
269   /// corresponding classof().
270   ///
271   /// We could pack these a bit tighter by not having the IK_FirstXXXInit
272   /// and IK_LastXXXInit be their own values, but that would degrade
273   /// readability for really no benefit.
274   enum InitKind : uint8_t {
275     IK_BitInit,
276     IK_FirstTypedInit,
277     IK_BitsInit,
278     IK_CodeInit,
279     IK_DagInit,
280     IK_DefInit,
281     IK_FieldInit,
282     IK_IntInit,
283     IK_ListInit,
284     IK_FirstOpInit,
285     IK_BinOpInit,
286     IK_TernOpInit,
287     IK_UnOpInit,
288     IK_LastOpInit,
289     IK_StringInit,
290     IK_VarInit,
291     IK_VarListElementInit,
292     IK_LastTypedInit,
293     IK_UnsetInit,
294     IK_VarBitInit
295   };
296
297 private:
298   const InitKind Kind;
299
300 protected:
301   uint8_t Opc; // Used by UnOpInit, BinOpInit, and TernOpInit
302
303 private:
304   virtual void anchor();
305
306 public:
307   InitKind getKind() const { return Kind; }
308
309 protected:
310   explicit Init(InitKind K, uint8_t Opc = 0) : Kind(K), Opc(Opc) {}
311
312 public:
313   Init(const Init &) = delete;
314   Init &operator=(const Init &) = delete;
315   virtual ~Init() = default;
316
317   /// This virtual method should be overridden by values that may
318   /// not be completely specified yet.
319   virtual bool isComplete() const { return true; }
320
321   /// Print out this value.
322   void print(raw_ostream &OS) const { OS << getAsString(); }
323
324   /// Convert this value to a string form.
325   virtual std::string getAsString() const = 0;
326   /// Convert this value to a string form,
327   /// without adding quote markers.  This primaruly affects
328   /// StringInits where we will not surround the string value with
329   /// quotes.
330   virtual std::string getAsUnquotedString() const { return getAsString(); }
331
332   /// Debugging method that may be called through a debugger, just
333   /// invokes print on stderr.
334   void dump() const;
335
336   /// This virtual function converts to the appropriate
337   /// Init based on the passed in type.
338   virtual Init *convertInitializerTo(RecTy *Ty) const = 0;
339
340   /// This method is used to implement the bitrange
341   /// selection operator.  Given an initializer, it selects the specified bits
342   /// out, returning them as a new init of bits type.  If it is not legal to use
343   /// the bit subscript operator on this initializer, return null.
344   ///
345   virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
346     return nullptr;
347   }
348
349   /// This method is used to implement the list slice
350   /// selection operator.  Given an initializer, it selects the specified list
351   /// elements, returning them as a new init of list type.  If it is not legal
352   /// to take a slice of this, return null.
353   ///
354   virtual Init *convertInitListSlice(ArrayRef<unsigned> Elements) const {
355     return nullptr;
356   }
357
358   /// This method is used to implement the FieldInit class.
359   /// Implementors of this method should return the type of the named field if
360   /// they are of record type.
361   ///
362   virtual RecTy *getFieldType(StringInit *FieldName) const {
363     return nullptr;
364   }
365
366   /// This method complements getFieldType to return the
367   /// initializer for the specified field.  If getFieldType returns non-null
368   /// this method should return non-null, otherwise it returns null.
369   ///
370   virtual Init *getFieldInit(Record &R, const RecordVal *RV,
371                              StringInit *FieldName) const {
372     return nullptr;
373   }
374
375   /// This method is used by classes that refer to other
376   /// variables which may not be defined at the time the expression is formed.
377   /// If a value is set for the variable later, this method will be called on
378   /// users of the value to allow the value to propagate out.
379   ///
380   virtual Init *resolveReferences(Record &R, const RecordVal *RV) const {
381     return const_cast<Init *>(this);
382   }
383
384   /// This method is used to return the initializer for the specified
385   /// bit.
386   virtual Init *getBit(unsigned Bit) const = 0;
387
388   /// This method is used to retrieve the initializer for bit
389   /// reference. For non-VarBitInit, it simply returns itself.
390   virtual Init *getBitVar() const { return const_cast<Init*>(this); }
391
392   /// This method is used to retrieve the bit number of a bit
393   /// reference. For non-VarBitInit, it simply returns 0.
394   virtual unsigned getBitNum() const { return 0; }
395 };
396
397 inline raw_ostream &operator<<(raw_ostream &OS, const Init &I) {
398   I.print(OS); return OS;
399 }
400
401 /// This is the common super-class of types that have a specific,
402 /// explicit, type.
403 ///
404 class TypedInit : public Init {
405   RecTy *Ty;
406
407 protected:
408   explicit TypedInit(InitKind K, RecTy *T, uint8_t Opc = 0)
409     : Init(K, Opc), Ty(T) {}
410
411 public:
412   TypedInit(const TypedInit &Other) = delete;
413   TypedInit &operator=(const TypedInit &Other) = delete;
414
415   static bool classof(const Init *I) {
416     return I->getKind() >= IK_FirstTypedInit &&
417            I->getKind() <= IK_LastTypedInit;
418   }
419
420   RecTy *getType() const { return Ty; }
421
422   Init *convertInitializerTo(RecTy *Ty) const override;
423
424   Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
425   Init *convertInitListSlice(ArrayRef<unsigned> Elements) const override;
426
427   /// This method is used to implement the FieldInit class.
428   /// Implementors of this method should return the type of the named field if
429   /// they are of record type.
430   ///
431   RecTy *getFieldType(StringInit *FieldName) const override;
432
433   /// This method is used to implement
434   /// VarListElementInit::resolveReferences.  If the list element is resolvable
435   /// now, we return the resolved value, otherwise we return null.
436   virtual Init *resolveListElementReference(Record &R, const RecordVal *RV,
437                                             unsigned Elt) const = 0;
438 };
439
440 /// '?' - Represents an uninitialized value
441 ///
442 class UnsetInit : public Init {
443   UnsetInit() : Init(IK_UnsetInit) {}
444
445 public:
446   UnsetInit(const UnsetInit &) = delete;
447   UnsetInit &operator=(const UnsetInit &Other) = delete;
448
449   static bool classof(const Init *I) {
450     return I->getKind() == IK_UnsetInit;
451   }
452
453   static UnsetInit *get();
454
455   Init *convertInitializerTo(RecTy *Ty) const override;
456
457   Init *getBit(unsigned Bit) const override {
458     return const_cast<UnsetInit*>(this);
459   }
460
461   bool isComplete() const override { return false; }
462   std::string getAsString() const override { return "?"; }
463 };
464
465 /// 'true'/'false' - Represent a concrete initializer for a bit.
466 ///
467 class BitInit : public Init {
468   bool Value;
469
470   explicit BitInit(bool V) : Init(IK_BitInit), Value(V) {}
471
472 public:
473   BitInit(const BitInit &Other) = delete;
474   BitInit &operator=(BitInit &Other) = delete;
475
476   static bool classof(const Init *I) {
477     return I->getKind() == IK_BitInit;
478   }
479
480   static BitInit *get(bool V);
481
482   bool getValue() const { return Value; }
483
484   Init *convertInitializerTo(RecTy *Ty) const override;
485
486   Init *getBit(unsigned Bit) const override {
487     assert(Bit < 1 && "Bit index out of range!");
488     return const_cast<BitInit*>(this);
489   }
490
491   std::string getAsString() const override { return Value ? "1" : "0"; }
492 };
493
494 /// '{ a, b, c }' - Represents an initializer for a BitsRecTy value.
495 /// It contains a vector of bits, whose size is determined by the type.
496 ///
497 class BitsInit final : public TypedInit, public FoldingSetNode,
498                        public TrailingObjects<BitsInit, Init *> {
499   unsigned NumBits;
500
501   BitsInit(unsigned N)
502     : TypedInit(IK_BitsInit, BitsRecTy::get(N)), NumBits(N) {}
503
504 public:
505   BitsInit(const BitsInit &Other) = delete;
506   BitsInit &operator=(const BitsInit &Other) = delete;
507
508   // Do not use sized deallocation due to trailing objects.
509   void operator delete(void *p) { ::operator delete(p); }
510
511   static bool classof(const Init *I) {
512     return I->getKind() == IK_BitsInit;
513   }
514
515   static BitsInit *get(ArrayRef<Init *> Range);
516
517   void Profile(FoldingSetNodeID &ID) const;
518
519   unsigned getNumBits() const { return NumBits; }
520
521   Init *convertInitializerTo(RecTy *Ty) const override;
522   Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
523
524   bool isComplete() const override {
525     for (unsigned i = 0; i != getNumBits(); ++i)
526       if (!getBit(i)->isComplete()) return false;
527     return true;
528   }
529
530   bool allInComplete() const {
531     for (unsigned i = 0; i != getNumBits(); ++i)
532       if (getBit(i)->isComplete()) return false;
533     return true;
534   }
535
536   std::string getAsString() const override;
537
538   /// This method is used to implement
539   /// VarListElementInit::resolveReferences.  If the list element is resolvable
540   /// now, we return the resolved value, otherwise we return null.
541   Init *resolveListElementReference(Record &R, const RecordVal *RV,
542                                     unsigned Elt) const override {
543     llvm_unreachable("Illegal element reference off bits<n>");
544   }
545
546   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
547
548   Init *getBit(unsigned Bit) const override {
549     assert(Bit < NumBits && "Bit index out of range!");
550     return getTrailingObjects<Init *>()[Bit];
551   }
552 };
553
554 /// '7' - Represent an initialization by a literal integer value.
555 ///
556 class IntInit : public TypedInit {
557   int64_t Value;
558
559   explicit IntInit(int64_t V)
560     : TypedInit(IK_IntInit, IntRecTy::get()), Value(V) {}
561
562 public:
563   IntInit(const IntInit &Other) = delete;
564   IntInit &operator=(const IntInit &Other) = delete;
565
566   static bool classof(const Init *I) {
567     return I->getKind() == IK_IntInit;
568   }
569
570   static IntInit *get(int64_t V);
571
572   int64_t getValue() const { return Value; }
573
574   Init *convertInitializerTo(RecTy *Ty) const override;
575   Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
576
577   std::string getAsString() const override;
578
579   /// This method is used to implement
580   /// VarListElementInit::resolveReferences.  If the list element is resolvable
581   /// now, we return the resolved value, otherwise we return null.
582   Init *resolveListElementReference(Record &R, const RecordVal *RV,
583                                     unsigned Elt) const override {
584     llvm_unreachable("Illegal element reference off int");
585   }
586
587   Init *getBit(unsigned Bit) const override {
588     return BitInit::get((Value & (1ULL << Bit)) != 0);
589   }
590 };
591
592 /// "foo" - Represent an initialization by a string value.
593 ///
594 class StringInit : public TypedInit {
595   StringRef Value;
596
597   explicit StringInit(StringRef V)
598       : TypedInit(IK_StringInit, StringRecTy::get()), Value(V) {}
599
600 public:
601   StringInit(const StringInit &Other) = delete;
602   StringInit &operator=(const StringInit &Other) = delete;
603
604   static bool classof(const Init *I) {
605     return I->getKind() == IK_StringInit;
606   }
607
608   static StringInit *get(StringRef);
609
610   StringRef getValue() const { return Value; }
611
612   Init *convertInitializerTo(RecTy *Ty) const override;
613
614   std::string getAsString() const override { return "\"" + Value.str() + "\""; }
615
616   std::string getAsUnquotedString() const override { return Value; }
617
618   /// resolveListElementReference - This method is used to implement
619   /// VarListElementInit::resolveReferences.  If the list element is resolvable
620   /// now, we return the resolved value, otherwise we return null.
621   Init *resolveListElementReference(Record &R, const RecordVal *RV,
622                                     unsigned Elt) const override {
623     llvm_unreachable("Illegal element reference off string");
624   }
625
626   Init *getBit(unsigned Bit) const override {
627     llvm_unreachable("Illegal bit reference off string");
628   }
629 };
630
631 class CodeInit : public TypedInit {
632   StringRef Value;
633
634   explicit CodeInit(StringRef V)
635       : TypedInit(IK_CodeInit, static_cast<RecTy *>(CodeRecTy::get())),
636         Value(V) {}
637
638 public:
639   CodeInit(const StringInit &Other) = delete;
640   CodeInit &operator=(const StringInit &Other) = delete;
641
642   static bool classof(const Init *I) {
643     return I->getKind() == IK_CodeInit;
644   }
645
646   static CodeInit *get(StringRef);
647
648   StringRef getValue() const { return Value; }
649
650   Init *convertInitializerTo(RecTy *Ty) const override;
651
652   std::string getAsString() const override {
653     return "[{" + Value.str() + "}]";
654   }
655
656   std::string getAsUnquotedString() const override { return Value; }
657
658   /// This method is used to implement
659   /// VarListElementInit::resolveReferences.  If the list element is resolvable
660   /// now, we return the resolved value, otherwise we return null.
661   Init *resolveListElementReference(Record &R, const RecordVal *RV,
662                                     unsigned Elt) const override {
663     llvm_unreachable("Illegal element reference off string");
664   }
665
666   Init *getBit(unsigned Bit) const override {
667     llvm_unreachable("Illegal bit reference off string");
668   }
669 };
670
671 /// [AL, AH, CL] - Represent a list of defs
672 ///
673 class ListInit final : public TypedInit, public FoldingSetNode,
674                        public TrailingObjects<BitsInit, Init *> {
675   unsigned NumValues;
676
677 public:
678   typedef Init *const *const_iterator;
679
680 private:
681   explicit ListInit(unsigned N, RecTy *EltTy)
682     : TypedInit(IK_ListInit, ListRecTy::get(EltTy)), NumValues(N) {}
683
684 public:
685   ListInit(const ListInit &Other) = delete;
686   ListInit &operator=(const ListInit &Other) = delete;
687
688   // Do not use sized deallocation due to trailing objects.
689   void operator delete(void *p) { ::operator delete(p); }
690
691   static bool classof(const Init *I) {
692     return I->getKind() == IK_ListInit;
693   }
694   static ListInit *get(ArrayRef<Init *> Range, RecTy *EltTy);
695
696   void Profile(FoldingSetNodeID &ID) const;
697
698   Init *getElement(unsigned i) const {
699     assert(i < NumValues && "List element index out of range!");
700     return getTrailingObjects<Init *>()[i];
701   }
702
703   Record *getElementAsRecord(unsigned i) const;
704
705   Init *convertInitListSlice(ArrayRef<unsigned> Elements) const override;
706
707   Init *convertInitializerTo(RecTy *Ty) const override;
708
709   /// This method is used by classes that refer to other
710   /// variables which may not be defined at the time they expression is formed.
711   /// If a value is set for the variable later, this method will be called on
712   /// users of the value to allow the value to propagate out.
713   ///
714   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
715
716   std::string getAsString() const override;
717
718   ArrayRef<Init*> getValues() const {
719     return makeArrayRef(getTrailingObjects<Init *>(), NumValues);
720   }
721
722   const_iterator begin() const { return getTrailingObjects<Init *>(); }
723   const_iterator end  () const { return begin() + NumValues; }
724
725   size_t         size () const { return NumValues;  }
726   bool           empty() const { return NumValues == 0; }
727
728   /// This method is used to implement
729   /// VarListElementInit::resolveReferences.  If the list element is resolvable
730   /// now, we return the resolved value, otherwise we return null.
731   Init *resolveListElementReference(Record &R, const RecordVal *RV,
732                                     unsigned Elt) const override;
733
734   Init *getBit(unsigned Bit) const override {
735     llvm_unreachable("Illegal bit reference off list");
736   }
737 };
738
739 /// Base class for operators
740 ///
741 class OpInit : public TypedInit {
742 protected:
743   explicit OpInit(InitKind K, RecTy *Type, uint8_t Opc)
744     : TypedInit(K, Type, Opc) {}
745
746 public:
747   OpInit(const OpInit &Other) = delete;
748   OpInit &operator=(OpInit &Other) = delete;
749
750   static bool classof(const Init *I) {
751     return I->getKind() >= IK_FirstOpInit &&
752            I->getKind() <= IK_LastOpInit;
753   }
754
755   // Clone - Clone this operator, replacing arguments with the new list
756   virtual OpInit *clone(ArrayRef<Init *> Operands) const = 0;
757
758   virtual unsigned getNumOperands() const = 0;
759   virtual Init *getOperand(unsigned i) const = 0;
760
761   // Fold - If possible, fold this to a simpler init.  Return this if not
762   // possible to fold.
763   virtual Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const = 0;
764
765   Init *resolveListElementReference(Record &R, const RecordVal *RV,
766                                     unsigned Elt) const override;
767
768   Init *getBit(unsigned Bit) const override;
769 };
770
771 /// !op (X) - Transform an init.
772 ///
773 class UnOpInit : public OpInit, public FoldingSetNode {
774 public:
775   enum UnaryOp : uint8_t { CAST, HEAD, TAIL, EMPTY };
776
777 private:
778   Init *LHS;
779
780   UnOpInit(UnaryOp opc, Init *lhs, RecTy *Type)
781     : OpInit(IK_UnOpInit, Type, opc), LHS(lhs) {}
782
783 public:
784   UnOpInit(const UnOpInit &Other) = delete;
785   UnOpInit &operator=(const UnOpInit &Other) = delete;
786
787   static bool classof(const Init *I) {
788     return I->getKind() == IK_UnOpInit;
789   }
790
791   static UnOpInit *get(UnaryOp opc, Init *lhs, RecTy *Type);
792
793   void Profile(FoldingSetNodeID &ID) const;
794
795   // Clone - Clone this operator, replacing arguments with the new list
796   OpInit *clone(ArrayRef<Init *> Operands) const override {
797     assert(Operands.size() == 1 &&
798            "Wrong number of operands for unary operation");
799     return UnOpInit::get(getOpcode(), *Operands.begin(), getType());
800   }
801
802   unsigned getNumOperands() const override { return 1; }
803
804   Init *getOperand(unsigned i) const override {
805     assert(i == 0 && "Invalid operand id for unary operator");
806     return getOperand();
807   }
808
809   UnaryOp getOpcode() const { return (UnaryOp)Opc; }
810   Init *getOperand() const { return LHS; }
811
812   // Fold - If possible, fold this to a simpler init.  Return this if not
813   // possible to fold.
814   Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const override;
815
816   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
817
818   std::string getAsString() const override;
819 };
820
821 /// !op (X, Y) - Combine two inits.
822 ///
823 class BinOpInit : public OpInit, public FoldingSetNode {
824 public:
825   enum BinaryOp : uint8_t { ADD, AND, OR, SHL, SRA, SRL, LISTCONCAT,
826                             STRCONCAT, CONCAT, EQ };
827
828 private:
829   Init *LHS, *RHS;
830
831   BinOpInit(BinaryOp opc, Init *lhs, Init *rhs, RecTy *Type) :
832       OpInit(IK_BinOpInit, Type, opc), LHS(lhs), RHS(rhs) {}
833
834 public:
835   BinOpInit(const BinOpInit &Other) = delete;
836   BinOpInit &operator=(const BinOpInit &Other) = delete;
837
838   static bool classof(const Init *I) {
839     return I->getKind() == IK_BinOpInit;
840   }
841
842   static BinOpInit *get(BinaryOp opc, Init *lhs, Init *rhs,
843                         RecTy *Type);
844
845   void Profile(FoldingSetNodeID &ID) const;
846
847   // Clone - Clone this operator, replacing arguments with the new list
848   OpInit *clone(ArrayRef<Init *> Operands) const override {
849     assert(Operands.size() == 2 &&
850            "Wrong number of operands for binary operation");
851     return BinOpInit::get(getOpcode(), Operands[0], Operands[1], getType());
852   }
853
854   unsigned getNumOperands() const override { return 2; }
855   Init *getOperand(unsigned i) const override {
856     switch (i) {
857     default: llvm_unreachable("Invalid operand id for binary operator");
858     case 0: return getLHS();
859     case 1: return getRHS();
860     }
861   }
862
863   BinaryOp getOpcode() const { return (BinaryOp)Opc; }
864   Init *getLHS() const { return LHS; }
865   Init *getRHS() const { return RHS; }
866
867   // Fold - If possible, fold this to a simpler init.  Return this if not
868   // possible to fold.
869   Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const override;
870
871   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
872
873   std::string getAsString() const override;
874 };
875
876 /// !op (X, Y, Z) - Combine two inits.
877 ///
878 class TernOpInit : public OpInit, public FoldingSetNode {
879 public:
880   enum TernaryOp : uint8_t { SUBST, FOREACH, IF };
881
882 private:
883   Init *LHS, *MHS, *RHS;
884
885   TernOpInit(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs,
886              RecTy *Type) :
887       OpInit(IK_TernOpInit, Type, opc), LHS(lhs), MHS(mhs), RHS(rhs) {}
888
889 public:
890   TernOpInit(const TernOpInit &Other) = delete;
891   TernOpInit &operator=(const TernOpInit &Other) = delete;
892
893   static bool classof(const Init *I) {
894     return I->getKind() == IK_TernOpInit;
895   }
896
897   static TernOpInit *get(TernaryOp opc, Init *lhs,
898                          Init *mhs, Init *rhs,
899                          RecTy *Type);
900
901   void Profile(FoldingSetNodeID &ID) const;
902
903   // Clone - Clone this operator, replacing arguments with the new list
904   OpInit *clone(ArrayRef<Init *> Operands) const override {
905     assert(Operands.size() == 3 &&
906            "Wrong number of operands for ternary operation");
907     return TernOpInit::get(getOpcode(), Operands[0], Operands[1], Operands[2],
908                            getType());
909   }
910
911   unsigned getNumOperands() const override { return 3; }
912   Init *getOperand(unsigned i) const override {
913     switch (i) {
914     default: llvm_unreachable("Invalid operand id for ternary operator");
915     case 0: return getLHS();
916     case 1: return getMHS();
917     case 2: return getRHS();
918     }
919   }
920
921   TernaryOp getOpcode() const { return (TernaryOp)Opc; }
922   Init *getLHS() const { return LHS; }
923   Init *getMHS() const { return MHS; }
924   Init *getRHS() const { return RHS; }
925
926   // Fold - If possible, fold this to a simpler init.  Return this if not
927   // possible to fold.
928   Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const override;
929
930   bool isComplete() const override { return false; }
931
932   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
933
934   std::string getAsString() const override;
935 };
936
937 /// 'Opcode' - Represent a reference to an entire variable object.
938 ///
939 class VarInit : public TypedInit {
940   Init *VarName;
941
942   explicit VarInit(Init *VN, RecTy *T)
943       : TypedInit(IK_VarInit, T), VarName(VN) {}
944
945 public:
946   VarInit(const VarInit &Other) = delete;
947   VarInit &operator=(const VarInit &Other) = delete;
948
949   static bool classof(const Init *I) {
950     return I->getKind() == IK_VarInit;
951   }
952
953   static VarInit *get(StringRef VN, RecTy *T);
954   static VarInit *get(Init *VN, RecTy *T);
955
956   StringRef getName() const;
957   Init *getNameInit() const { return VarName; }
958
959   std::string getNameInitAsString() const {
960     return getNameInit()->getAsUnquotedString();
961   }
962
963   Init *resolveListElementReference(Record &R, const RecordVal *RV,
964                                     unsigned Elt) const override;
965
966   RecTy *getFieldType(StringInit *FieldName) const override;
967   Init *getFieldInit(Record &R, const RecordVal *RV,
968                      StringInit *FieldName) const override;
969
970   /// This method is used by classes that refer to other
971   /// variables which may not be defined at the time they expression is formed.
972   /// If a value is set for the variable later, this method will be called on
973   /// users of the value to allow the value to propagate out.
974   ///
975   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
976
977   Init *getBit(unsigned Bit) const override;
978
979   std::string getAsString() const override { return getName(); }
980 };
981
982 /// Opcode{0} - Represent access to one bit of a variable or field.
983 ///
984 class VarBitInit : public Init {
985   TypedInit *TI;
986   unsigned Bit;
987
988   VarBitInit(TypedInit *T, unsigned B) : Init(IK_VarBitInit), TI(T), Bit(B) {
989     assert(T->getType() &&
990            (isa<IntRecTy>(T->getType()) ||
991             (isa<BitsRecTy>(T->getType()) &&
992              cast<BitsRecTy>(T->getType())->getNumBits() > B)) &&
993            "Illegal VarBitInit expression!");
994   }
995
996 public:
997   VarBitInit(const VarBitInit &Other) = delete;
998   VarBitInit &operator=(const VarBitInit &Other) = delete;
999
1000   static bool classof(const Init *I) {
1001     return I->getKind() == IK_VarBitInit;
1002   }
1003
1004   static VarBitInit *get(TypedInit *T, unsigned B);
1005
1006   Init *convertInitializerTo(RecTy *Ty) const override;
1007
1008   Init *getBitVar() const override { return TI; }
1009   unsigned getBitNum() const override { return Bit; }
1010
1011   std::string getAsString() const override;
1012   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
1013
1014   Init *getBit(unsigned B) const override {
1015     assert(B < 1 && "Bit index out of range!");
1016     return const_cast<VarBitInit*>(this);
1017   }
1018 };
1019
1020 /// List[4] - Represent access to one element of a var or
1021 /// field.
1022 class VarListElementInit : public TypedInit {
1023   TypedInit *TI;
1024   unsigned Element;
1025
1026   VarListElementInit(TypedInit *T, unsigned E)
1027       : TypedInit(IK_VarListElementInit,
1028                   cast<ListRecTy>(T->getType())->getElementType()),
1029         TI(T), Element(E) {
1030     assert(T->getType() && isa<ListRecTy>(T->getType()) &&
1031            "Illegal VarBitInit expression!");
1032   }
1033
1034 public:
1035   VarListElementInit(const VarListElementInit &Other) = delete;
1036   void operator=(const VarListElementInit &Other) = delete;
1037
1038   static bool classof(const Init *I) {
1039     return I->getKind() == IK_VarListElementInit;
1040   }
1041
1042   static VarListElementInit *get(TypedInit *T, unsigned E);
1043
1044   TypedInit *getVariable() const { return TI; }
1045   unsigned getElementNum() const { return Element; }
1046
1047   /// This method is used to implement
1048   /// VarListElementInit::resolveReferences.  If the list element is resolvable
1049   /// now, we return the resolved value, otherwise we return null.
1050   Init *resolveListElementReference(Record &R, const RecordVal *RV,
1051                                     unsigned Elt) const override;
1052
1053   std::string getAsString() const override;
1054   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
1055
1056   Init *getBit(unsigned Bit) const override;
1057 };
1058
1059 /// AL - Represent a reference to a 'def' in the description
1060 ///
1061 class DefInit : public TypedInit {
1062   Record *Def;
1063
1064   DefInit(Record *D, RecordRecTy *T) : TypedInit(IK_DefInit, T), Def(D) {}
1065
1066   friend class Record;
1067
1068 public:
1069   DefInit(const DefInit &Other) = delete;
1070   DefInit &operator=(const DefInit &Other) = delete;
1071
1072   static bool classof(const Init *I) {
1073     return I->getKind() == IK_DefInit;
1074   }
1075
1076   static DefInit *get(Record*);
1077
1078   Init *convertInitializerTo(RecTy *Ty) const override;
1079
1080   Record *getDef() const { return Def; }
1081
1082   //virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits);
1083
1084   RecTy *getFieldType(StringInit *FieldName) const override;
1085   Init *getFieldInit(Record &R, const RecordVal *RV,
1086                      StringInit *FieldName) const override;
1087
1088   std::string getAsString() const override;
1089
1090   Init *getBit(unsigned Bit) const override {
1091     llvm_unreachable("Illegal bit reference off def");
1092   }
1093
1094   /// This method is used to implement
1095   /// VarListElementInit::resolveReferences.  If the list element is resolvable
1096   /// now, we return the resolved value, otherwise we return null.
1097   Init *resolveListElementReference(Record &R, const RecordVal *RV,
1098                                     unsigned Elt) const override {
1099     llvm_unreachable("Illegal element reference off def");
1100   }
1101 };
1102
1103 /// X.Y - Represent a reference to a subfield of a variable
1104 ///
1105 class FieldInit : public TypedInit {
1106   Init *Rec;                // Record we are referring to
1107   StringInit *FieldName;    // Field we are accessing
1108
1109   FieldInit(Init *R, StringInit *FN)
1110       : TypedInit(IK_FieldInit, R->getFieldType(FN)), Rec(R), FieldName(FN) {
1111     assert(getType() && "FieldInit with non-record type!");
1112   }
1113
1114 public:
1115   FieldInit(const FieldInit &Other) = delete;
1116   FieldInit &operator=(const FieldInit &Other) = delete;
1117
1118   static bool classof(const Init *I) {
1119     return I->getKind() == IK_FieldInit;
1120   }
1121
1122   static FieldInit *get(Init *R, StringInit *FN);
1123
1124   Init *getBit(unsigned Bit) const override;
1125
1126   Init *resolveListElementReference(Record &R, const RecordVal *RV,
1127                                     unsigned Elt) const override;
1128
1129   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
1130
1131   std::string getAsString() const override {
1132     return Rec->getAsString() + "." + FieldName->getValue().str();
1133   }
1134 };
1135
1136 /// (v a, b) - Represent a DAG tree value.  DAG inits are required
1137 /// to have at least one value then a (possibly empty) list of arguments.  Each
1138 /// argument can have a name associated with it.
1139 ///
1140 class DagInit : public TypedInit, public FoldingSetNode {
1141   Init *Val;
1142   StringInit *ValName;
1143   SmallVector<Init*, 4> Args;
1144   SmallVector<StringInit*, 4> ArgNames;
1145
1146   DagInit(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
1147           ArrayRef<StringInit *> NameRange)
1148       : TypedInit(IK_DagInit, DagRecTy::get()), Val(V), ValName(VN),
1149           Args(ArgRange.begin(), ArgRange.end()),
1150           ArgNames(NameRange.begin(), NameRange.end()) {}
1151
1152 public:
1153   DagInit(const DagInit &Other) = delete;
1154   DagInit &operator=(const DagInit &Other) = delete;
1155
1156   static bool classof(const Init *I) {
1157     return I->getKind() == IK_DagInit;
1158   }
1159
1160   static DagInit *get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
1161                       ArrayRef<StringInit*> NameRange);
1162   static DagInit *get(Init *V, StringInit *VN,
1163                       ArrayRef<std::pair<Init*, StringInit*>> Args);
1164
1165   void Profile(FoldingSetNodeID &ID) const;
1166
1167   Init *convertInitializerTo(RecTy *Ty) const override;
1168
1169   Init *getOperator() const { return Val; }
1170
1171   StringInit *getName() const { return ValName; }
1172   StringRef getNameStr() const {
1173     return ValName ? ValName->getValue() : StringRef();
1174   }
1175
1176   unsigned getNumArgs() const { return Args.size(); }
1177   Init *getArg(unsigned Num) const {
1178     assert(Num < Args.size() && "Arg number out of range!");
1179     return Args[Num];
1180   }
1181   StringInit *getArgName(unsigned Num) const {
1182     assert(Num < ArgNames.size() && "Arg number out of range!");
1183     return ArgNames[Num];
1184   }
1185   StringRef getArgNameStr(unsigned Num) const {
1186     StringInit *Init = getArgName(Num);
1187     return Init ? Init->getValue() : StringRef();
1188   }
1189
1190   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
1191
1192   std::string getAsString() const override;
1193
1194   typedef SmallVectorImpl<Init*>::const_iterator       const_arg_iterator;
1195   typedef SmallVectorImpl<StringInit*>::const_iterator const_name_iterator;
1196
1197   inline const_arg_iterator  arg_begin() const { return Args.begin(); }
1198   inline const_arg_iterator  arg_end  () const { return Args.end();   }
1199
1200   inline size_t              arg_size () const { return Args.size();  }
1201   inline bool                arg_empty() const { return Args.empty(); }
1202
1203   inline const_name_iterator name_begin() const { return ArgNames.begin(); }
1204   inline const_name_iterator name_end  () const { return ArgNames.end();   }
1205
1206   inline size_t              name_size () const { return ArgNames.size();  }
1207   inline bool                name_empty() const { return ArgNames.empty(); }
1208
1209   Init *getBit(unsigned Bit) const override {
1210     llvm_unreachable("Illegal bit reference off dag");
1211   }
1212
1213   Init *resolveListElementReference(Record &R, const RecordVal *RV,
1214                                     unsigned Elt) const override {
1215     llvm_unreachable("Illegal element reference off dag");
1216   }
1217 };
1218
1219 //===----------------------------------------------------------------------===//
1220 //  High-Level Classes
1221 //===----------------------------------------------------------------------===//
1222
1223 class RecordVal {
1224   friend class Record;
1225   Init *Name;
1226   PointerIntPair<RecTy *, 1, bool> TyAndPrefix;
1227   Init *Value;
1228
1229 public:
1230   RecordVal(Init *N, RecTy *T, bool P);
1231   RecordVal(StringRef N, RecTy *T, bool P);
1232
1233   StringRef getName() const;
1234   Init *getNameInit() const { return Name; }
1235
1236   std::string getNameInitAsString() const {
1237     return getNameInit()->getAsUnquotedString();
1238   }
1239
1240   bool getPrefix() const { return TyAndPrefix.getInt(); }
1241   RecTy *getType() const { return TyAndPrefix.getPointer(); }
1242   Init *getValue() const { return Value; }
1243
1244   bool setValue(Init *V) {
1245     if (V) {
1246       Value = V->convertInitializerTo(getType());
1247       return Value == nullptr;
1248     }
1249     Value = nullptr;
1250     return false;
1251   }
1252
1253   void dump() const;
1254   void print(raw_ostream &OS, bool PrintSem = true) const;
1255 };
1256
1257 inline raw_ostream &operator<<(raw_ostream &OS, const RecordVal &RV) {
1258   RV.print(OS << "  ");
1259   return OS;
1260 }
1261
1262 class Record {
1263   static unsigned LastID;
1264
1265   Init *Name;
1266   // Location where record was instantiated, followed by the location of
1267   // multiclass prototypes used.
1268   SmallVector<SMLoc, 4> Locs;
1269   SmallVector<Init *, 0> TemplateArgs;
1270   SmallVector<RecordVal, 0> Values;
1271   SmallVector<std::pair<Record *, SMRange>, 0> SuperClasses;
1272
1273   // Tracks Record instances. Not owned by Record.
1274   RecordKeeper &TrackedRecords;
1275
1276   DefInit *TheInit = nullptr;
1277
1278   // Unique record ID.
1279   unsigned ID;
1280
1281   bool IsAnonymous;
1282
1283   // Class-instance values can be used by other defs.  For example, Struct<i>
1284   // is used here as a template argument to another class:
1285   //
1286   //   multiclass MultiClass<int i> {
1287   //     def Def : Class<Struct<i>>;
1288   //
1289   // These need to get fully resolved before instantiating any other
1290   // definitions that use them (e.g. Def).  However, inside a multiclass they
1291   // can't be immediately resolved so we mark them ResolveFirst to fully
1292   // resolve them later as soon as the multiclass is instantiated.
1293   bool ResolveFirst;
1294
1295   void init();
1296   void checkName();
1297
1298 public:
1299   // Constructs a record.
1300   explicit Record(Init *N, ArrayRef<SMLoc> locs, RecordKeeper &records,
1301                   bool Anonymous = false) :
1302     Name(N), Locs(locs.begin(), locs.end()), TrackedRecords(records),
1303     ID(LastID++), IsAnonymous(Anonymous), ResolveFirst(false) {
1304     init();
1305   }
1306
1307   explicit Record(StringRef N, ArrayRef<SMLoc> locs, RecordKeeper &records,
1308                   bool Anonymous = false)
1309     : Record(StringInit::get(N), locs, records, Anonymous) {}
1310
1311   // When copy-constructing a Record, we must still guarantee a globally unique
1312   // ID number.  Don't copy TheInit either since it's owned by the original
1313   // record. All other fields can be copied normally.
1314   Record(const Record &O) :
1315     Name(O.Name), Locs(O.Locs), TemplateArgs(O.TemplateArgs),
1316     Values(O.Values), SuperClasses(O.SuperClasses),
1317     TrackedRecords(O.TrackedRecords), ID(LastID++),
1318     IsAnonymous(O.IsAnonymous), ResolveFirst(O.ResolveFirst) { }
1319
1320   static unsigned getNewUID() { return LastID++; }
1321
1322   unsigned getID() const { return ID; }
1323
1324   StringRef getName() const;
1325   Init *getNameInit() const {
1326     return Name;
1327   }
1328
1329   const std::string getNameInitAsString() const {
1330     return getNameInit()->getAsUnquotedString();
1331   }
1332
1333   void setName(Init *Name);      // Also updates RecordKeeper.
1334   void setName(StringRef Name);  // Also updates RecordKeeper.
1335
1336   ArrayRef<SMLoc> getLoc() const { return Locs; }
1337
1338   /// get the corresponding DefInit.
1339   DefInit *getDefInit();
1340
1341   ArrayRef<Init *> getTemplateArgs() const {
1342     return TemplateArgs;
1343   }
1344
1345   ArrayRef<RecordVal> getValues() const { return Values; }
1346
1347   ArrayRef<std::pair<Record *, SMRange>>  getSuperClasses() const {
1348     return SuperClasses;
1349   }
1350
1351   bool isTemplateArg(Init *Name) const {
1352     for (Init *TA : TemplateArgs)
1353       if (TA == Name) return true;
1354     return false;
1355   }
1356
1357   bool isTemplateArg(StringRef Name) const {
1358     return isTemplateArg(StringInit::get(Name));
1359   }
1360
1361   const RecordVal *getValue(const Init *Name) const {
1362     for (const RecordVal &Val : Values)
1363       if (Val.Name == Name) return &Val;
1364     return nullptr;
1365   }
1366
1367   const RecordVal *getValue(StringRef Name) const {
1368     return getValue(StringInit::get(Name));
1369   }
1370
1371   RecordVal *getValue(const Init *Name) {
1372     for (RecordVal &Val : Values)
1373       if (Val.Name == Name) return &Val;
1374     return nullptr;
1375   }
1376
1377   RecordVal *getValue(StringRef Name) {
1378     return getValue(StringInit::get(Name));
1379   }
1380
1381   void addTemplateArg(Init *Name) {
1382     assert(!isTemplateArg(Name) && "Template arg already defined!");
1383     TemplateArgs.push_back(Name);
1384   }
1385
1386   void addTemplateArg(StringRef Name) {
1387     addTemplateArg(StringInit::get(Name));
1388   }
1389
1390   void addValue(const RecordVal &RV) {
1391     assert(getValue(RV.getNameInit()) == nullptr && "Value already added!");
1392     Values.push_back(RV);
1393     if (Values.size() > 1)
1394       // Keep NAME at the end of the list.  It makes record dumps a
1395       // bit prettier and allows TableGen tests to be written more
1396       // naturally.  Tests can use CHECK-NEXT to look for Record
1397       // fields they expect to see after a def.  They can't do that if
1398       // NAME is the first Record field.
1399       std::swap(Values[Values.size() - 2], Values[Values.size() - 1]);
1400   }
1401
1402   void removeValue(Init *Name) {
1403     for (unsigned i = 0, e = Values.size(); i != e; ++i)
1404       if (Values[i].getNameInit() == Name) {
1405         Values.erase(Values.begin()+i);
1406         return;
1407       }
1408     llvm_unreachable("Cannot remove an entry that does not exist!");
1409   }
1410
1411   void removeValue(StringRef Name) {
1412     removeValue(StringInit::get(Name));
1413   }
1414
1415   bool isSubClassOf(const Record *R) const {
1416     for (const auto &SCPair : SuperClasses)
1417       if (SCPair.first == R)
1418         return true;
1419     return false;
1420   }
1421
1422   bool isSubClassOf(StringRef Name) const {
1423     for (const auto &SCPair : SuperClasses) {
1424       if (const auto *SI = dyn_cast<StringInit>(SCPair.first->getNameInit())) {
1425         if (SI->getValue() == Name)
1426           return true;
1427       } else if (SCPair.first->getNameInitAsString() == Name) {
1428         return true;
1429       }
1430     }
1431     return false;
1432   }
1433
1434   void addSuperClass(Record *R, SMRange Range) {
1435     assert(!isSubClassOf(R) && "Already subclassing record!");
1436     SuperClasses.push_back(std::make_pair(R, Range));
1437   }
1438
1439   /// If there are any field references that refer to fields
1440   /// that have been filled in, we can propagate the values now.
1441   ///
1442   void resolveReferences() { resolveReferencesTo(nullptr); }
1443
1444   /// If anything in this record refers to RV, replace the
1445   /// reference to RV with the RHS of RV.  If RV is null, we resolve all
1446   /// possible references.
1447   void resolveReferencesTo(const RecordVal *RV);
1448
1449   RecordKeeper &getRecords() const {
1450     return TrackedRecords;
1451   }
1452
1453   bool isAnonymous() const {
1454     return IsAnonymous;
1455   }
1456
1457   bool isResolveFirst() const {
1458     return ResolveFirst;
1459   }
1460
1461   void setResolveFirst(bool b) {
1462     ResolveFirst = b;
1463   }
1464
1465   void dump() const;
1466
1467   //===--------------------------------------------------------------------===//
1468   // High-level methods useful to tablegen back-ends
1469   //
1470
1471   /// Return the initializer for a value with the specified name,
1472   /// or throw an exception if the field does not exist.
1473   ///
1474   Init *getValueInit(StringRef FieldName) const;
1475
1476   /// Return true if the named field is unset.
1477   bool isValueUnset(StringRef FieldName) const {
1478     return isa<UnsetInit>(getValueInit(FieldName));
1479   }
1480
1481   /// This method looks up the specified field and returns
1482   /// its value as a string, throwing an exception if the field does not exist
1483   /// or if the value is not a string.
1484   ///
1485   std::string getValueAsString(StringRef FieldName) const;
1486
1487   /// This method looks up the specified field and returns
1488   /// its value as a BitsInit, throwing an exception if the field does not exist
1489   /// or if the value is not the right type.
1490   ///
1491   BitsInit *getValueAsBitsInit(StringRef FieldName) const;
1492
1493   /// This method looks up the specified field and returns
1494   /// its value as a ListInit, throwing an exception if the field does not exist
1495   /// or if the value is not the right type.
1496   ///
1497   ListInit *getValueAsListInit(StringRef FieldName) const;
1498
1499   /// This method looks up the specified field and
1500   /// returns its value as a vector of records, throwing an exception if the
1501   /// field does not exist or if the value is not the right type.
1502   ///
1503   std::vector<Record*> getValueAsListOfDefs(StringRef FieldName) const;
1504
1505   /// This method looks up the specified field and
1506   /// returns its value as a vector of integers, throwing an exception if the
1507   /// field does not exist or if the value is not the right type.
1508   ///
1509   std::vector<int64_t> getValueAsListOfInts(StringRef FieldName) const;
1510
1511   /// This method looks up the specified field and
1512   /// returns its value as a vector of strings, throwing an exception if the
1513   /// field does not exist or if the value is not the right type.
1514   ///
1515   std::vector<std::string> getValueAsListOfStrings(StringRef FieldName) const;
1516
1517   /// This method looks up the specified field and returns its
1518   /// value as a Record, throwing an exception if the field does not exist or if
1519   /// the value is not the right type.
1520   ///
1521   Record *getValueAsDef(StringRef FieldName) const;
1522
1523   /// This method looks up the specified field and returns its
1524   /// value as a bit, throwing an exception if the field does not exist or if
1525   /// the value is not the right type.
1526   ///
1527   bool getValueAsBit(StringRef FieldName) const;
1528
1529   /// This method looks up the specified field and
1530   /// returns its value as a bit. If the field is unset, sets Unset to true and
1531   /// returns false.
1532   ///
1533   bool getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const;
1534
1535   /// This method looks up the specified field and returns its
1536   /// value as an int64_t, throwing an exception if the field does not exist or
1537   /// if the value is not the right type.
1538   ///
1539   int64_t getValueAsInt(StringRef FieldName) const;
1540
1541   /// This method looks up the specified field and returns its
1542   /// value as an Dag, throwing an exception if the field does not exist or if
1543   /// the value is not the right type.
1544   ///
1545   DagInit *getValueAsDag(StringRef FieldName) const;
1546 };
1547
1548 raw_ostream &operator<<(raw_ostream &OS, const Record &R);
1549
1550 struct MultiClass {
1551   Record Rec;  // Placeholder for template args and Name.
1552   typedef std::vector<std::unique_ptr<Record>> RecordVector;
1553   RecordVector DefPrototypes;
1554
1555   void dump() const;
1556
1557   MultiClass(StringRef Name, SMLoc Loc, RecordKeeper &Records) :
1558     Rec(Name, Loc, Records) {}
1559 };
1560
1561 class RecordKeeper {
1562   typedef std::map<std::string, std::unique_ptr<Record>> RecordMap;
1563   RecordMap Classes, Defs;
1564
1565 public:
1566   const RecordMap &getClasses() const { return Classes; }
1567   const RecordMap &getDefs() const { return Defs; }
1568
1569   Record *getClass(StringRef Name) const {
1570     auto I = Classes.find(Name);
1571     return I == Classes.end() ? nullptr : I->second.get();
1572   }
1573
1574   Record *getDef(StringRef Name) const {
1575     auto I = Defs.find(Name);
1576     return I == Defs.end() ? nullptr : I->second.get();
1577   }
1578
1579   void addClass(std::unique_ptr<Record> R) {
1580     bool Ins = Classes.insert(std::make_pair(R->getName(),
1581                                              std::move(R))).second;
1582     (void)Ins;
1583     assert(Ins && "Class already exists");
1584   }
1585
1586   void addDef(std::unique_ptr<Record> R) {
1587     bool Ins = Defs.insert(std::make_pair(R->getName(),
1588                                           std::move(R))).second;
1589     (void)Ins;
1590     assert(Ins && "Record already exists");
1591   }
1592
1593   //===--------------------------------------------------------------------===//
1594   // High-level helper methods, useful for tablegen backends...
1595
1596   /// This method returns all concrete definitions
1597   /// that derive from the specified class name.  A class with the specified
1598   /// name must exist.
1599   std::vector<Record *> getAllDerivedDefinitions(StringRef ClassName) const;
1600
1601   void dump() const;
1602 };
1603
1604 /// Sorting predicate to sort record pointers by name.
1605 ///
1606 struct LessRecord {
1607   bool operator()(const Record *Rec1, const Record *Rec2) const {
1608     return StringRef(Rec1->getName()).compare_numeric(Rec2->getName()) < 0;
1609   }
1610 };
1611
1612 /// Sorting predicate to sort record pointers by their
1613 /// unique ID. If you just need a deterministic order, use this, since it
1614 /// just compares two `unsigned`; the other sorting predicates require
1615 /// string manipulation.
1616 struct LessRecordByID {
1617   bool operator()(const Record *LHS, const Record *RHS) const {
1618     return LHS->getID() < RHS->getID();
1619   }
1620 };
1621
1622 /// Sorting predicate to sort record pointers by their
1623 /// name field.
1624 ///
1625 struct LessRecordFieldName {
1626   bool operator()(const Record *Rec1, const Record *Rec2) const {
1627     return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name");
1628   }
1629 };
1630
1631 struct LessRecordRegister {
1632   static bool ascii_isdigit(char x) { return x >= '0' && x <= '9'; }
1633
1634   struct RecordParts {
1635     SmallVector<std::pair< bool, StringRef>, 4> Parts;
1636
1637     RecordParts(StringRef Rec) {
1638       if (Rec.empty())
1639         return;
1640
1641       size_t Len = 0;
1642       const char *Start = Rec.data();
1643       const char *Curr = Start;
1644       bool isDigitPart = ascii_isdigit(Curr[0]);
1645       for (size_t I = 0, E = Rec.size(); I != E; ++I, ++Len) {
1646         bool isDigit = ascii_isdigit(Curr[I]);
1647         if (isDigit != isDigitPart) {
1648           Parts.push_back(std::make_pair(isDigitPart, StringRef(Start, Len)));
1649           Len = 0;
1650           Start = &Curr[I];
1651           isDigitPart = ascii_isdigit(Curr[I]);
1652         }
1653       }
1654       // Push the last part.
1655       Parts.push_back(std::make_pair(isDigitPart, StringRef(Start, Len)));
1656     }
1657
1658     size_t size() { return Parts.size(); }
1659
1660     std::pair<bool, StringRef> getPart(size_t i) {
1661       assert (i < Parts.size() && "Invalid idx!");
1662       return Parts[i];
1663     }
1664   };
1665
1666   bool operator()(const Record *Rec1, const Record *Rec2) const {
1667     RecordParts LHSParts(StringRef(Rec1->getName()));
1668     RecordParts RHSParts(StringRef(Rec2->getName()));
1669
1670     size_t LHSNumParts = LHSParts.size();
1671     size_t RHSNumParts = RHSParts.size();
1672     assert (LHSNumParts && RHSNumParts && "Expected at least one part!");
1673
1674     if (LHSNumParts != RHSNumParts)
1675       return LHSNumParts < RHSNumParts;
1676
1677     // We expect the registers to be of the form [_a-zA-z]+([0-9]*[_a-zA-Z]*)*.
1678     for (size_t I = 0, E = LHSNumParts; I < E; I+=2) {
1679       std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
1680       std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
1681       // Expect even part to always be alpha.
1682       assert (LHSPart.first == false && RHSPart.first == false &&
1683               "Expected both parts to be alpha.");
1684       if (int Res = LHSPart.second.compare(RHSPart.second))
1685         return Res < 0;
1686     }
1687     for (size_t I = 1, E = LHSNumParts; I < E; I+=2) {
1688       std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
1689       std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
1690       // Expect odd part to always be numeric.
1691       assert (LHSPart.first == true && RHSPart.first == true &&
1692               "Expected both parts to be numeric.");
1693       if (LHSPart.second.size() != RHSPart.second.size())
1694         return LHSPart.second.size() < RHSPart.second.size();
1695
1696       unsigned LHSVal, RHSVal;
1697
1698       bool LHSFailed = LHSPart.second.getAsInteger(10, LHSVal); (void)LHSFailed;
1699       assert(!LHSFailed && "Unable to convert LHS to integer.");
1700       bool RHSFailed = RHSPart.second.getAsInteger(10, RHSVal); (void)RHSFailed;
1701       assert(!RHSFailed && "Unable to convert RHS to integer.");
1702
1703       if (LHSVal != RHSVal)
1704         return LHSVal < RHSVal;
1705     }
1706     return LHSNumParts < RHSNumParts;
1707   }
1708 };
1709
1710 raw_ostream &operator<<(raw_ostream &OS, const RecordKeeper &RK);
1711
1712 /// Return an Init with a qualifier prefix referring
1713 /// to CurRec's name.
1714 Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1715                   Init *Name, StringRef Scoper);
1716
1717 } // end namespace llvm
1718
1719 #endif // LLVM_TABLEGEN_RECORD_H