]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/TableGen/Record.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304460, and update
[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<ListInit, 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 final : public TypedInit, public FoldingSetNode,
1141                       public TrailingObjects<DagInit, Init *, StringInit *> {
1142   Init *Val;
1143   StringInit *ValName;
1144   unsigned NumArgs;
1145   unsigned NumArgNames;
1146
1147   DagInit(Init *V, StringInit *VN, unsigned NumArgs, unsigned NumArgNames)
1148       : TypedInit(IK_DagInit, DagRecTy::get()), Val(V), ValName(VN),
1149         NumArgs(NumArgs), NumArgNames(NumArgNames) {}
1150
1151   friend TrailingObjects;
1152   size_t numTrailingObjects(OverloadToken<Init *>) const { return NumArgs; }
1153
1154 public:
1155   DagInit(const DagInit &Other) = delete;
1156   DagInit &operator=(const DagInit &Other) = delete;
1157
1158   static bool classof(const Init *I) {
1159     return I->getKind() == IK_DagInit;
1160   }
1161
1162   static DagInit *get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
1163                       ArrayRef<StringInit*> NameRange);
1164   static DagInit *get(Init *V, StringInit *VN,
1165                       ArrayRef<std::pair<Init*, StringInit*>> Args);
1166
1167   void Profile(FoldingSetNodeID &ID) const;
1168
1169   Init *convertInitializerTo(RecTy *Ty) const override;
1170
1171   Init *getOperator() const { return Val; }
1172
1173   StringInit *getName() const { return ValName; }
1174   StringRef getNameStr() const {
1175     return ValName ? ValName->getValue() : StringRef();
1176   }
1177
1178   unsigned getNumArgs() const { return NumArgs; }
1179   Init *getArg(unsigned Num) const {
1180     assert(Num < NumArgs && "Arg number out of range!");
1181     return getTrailingObjects<Init *>()[Num];
1182   }
1183   StringInit *getArgName(unsigned Num) const {
1184     assert(Num < NumArgNames && "Arg number out of range!");
1185     return getTrailingObjects<StringInit *>()[Num];
1186   }
1187   StringRef getArgNameStr(unsigned Num) const {
1188     StringInit *Init = getArgName(Num);
1189     return Init ? Init->getValue() : StringRef();
1190   }
1191
1192   ArrayRef<Init *> getArgs() const {
1193     return makeArrayRef(getTrailingObjects<Init *>(), NumArgs);
1194   }
1195   ArrayRef<StringInit *> getArgNames() const {
1196     return makeArrayRef(getTrailingObjects<StringInit *>(), NumArgNames);
1197   }
1198
1199   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
1200
1201   std::string getAsString() const override;
1202
1203   typedef SmallVectorImpl<Init*>::const_iterator       const_arg_iterator;
1204   typedef SmallVectorImpl<StringInit*>::const_iterator const_name_iterator;
1205
1206   inline const_arg_iterator  arg_begin() const { return getArgs().begin(); }
1207   inline const_arg_iterator  arg_end  () const { return getArgs().end(); }
1208
1209   inline size_t              arg_size () const { return NumArgs; }
1210   inline bool                arg_empty() const { return NumArgs == 0; }
1211
1212   inline const_name_iterator name_begin() const { return getArgNames().begin();}
1213   inline const_name_iterator name_end  () const { return getArgNames().end(); }
1214
1215   inline size_t              name_size () const { return NumArgNames; }
1216   inline bool                name_empty() const { return NumArgNames == 0; }
1217
1218   Init *getBit(unsigned Bit) const override {
1219     llvm_unreachable("Illegal bit reference off dag");
1220   }
1221
1222   Init *resolveListElementReference(Record &R, const RecordVal *RV,
1223                                     unsigned Elt) const override {
1224     llvm_unreachable("Illegal element reference off dag");
1225   }
1226 };
1227
1228 //===----------------------------------------------------------------------===//
1229 //  High-Level Classes
1230 //===----------------------------------------------------------------------===//
1231
1232 class RecordVal {
1233   friend class Record;
1234   Init *Name;
1235   PointerIntPair<RecTy *, 1, bool> TyAndPrefix;
1236   Init *Value;
1237
1238 public:
1239   RecordVal(Init *N, RecTy *T, bool P);
1240
1241   StringRef getName() const;
1242   Init *getNameInit() const { return Name; }
1243
1244   std::string getNameInitAsString() const {
1245     return getNameInit()->getAsUnquotedString();
1246   }
1247
1248   bool getPrefix() const { return TyAndPrefix.getInt(); }
1249   RecTy *getType() const { return TyAndPrefix.getPointer(); }
1250   Init *getValue() const { return Value; }
1251
1252   bool setValue(Init *V) {
1253     if (V) {
1254       Value = V->convertInitializerTo(getType());
1255       return Value == nullptr;
1256     }
1257     Value = nullptr;
1258     return false;
1259   }
1260
1261   void dump() const;
1262   void print(raw_ostream &OS, bool PrintSem = true) const;
1263 };
1264
1265 inline raw_ostream &operator<<(raw_ostream &OS, const RecordVal &RV) {
1266   RV.print(OS << "  ");
1267   return OS;
1268 }
1269
1270 class Record {
1271   static unsigned LastID;
1272
1273   Init *Name;
1274   // Location where record was instantiated, followed by the location of
1275   // multiclass prototypes used.
1276   SmallVector<SMLoc, 4> Locs;
1277   SmallVector<Init *, 0> TemplateArgs;
1278   SmallVector<RecordVal, 0> Values;
1279   SmallVector<std::pair<Record *, SMRange>, 0> SuperClasses;
1280
1281   // Tracks Record instances. Not owned by Record.
1282   RecordKeeper &TrackedRecords;
1283
1284   DefInit *TheInit = nullptr;
1285
1286   // Unique record ID.
1287   unsigned ID;
1288
1289   bool IsAnonymous;
1290
1291   // Class-instance values can be used by other defs.  For example, Struct<i>
1292   // is used here as a template argument to another class:
1293   //
1294   //   multiclass MultiClass<int i> {
1295   //     def Def : Class<Struct<i>>;
1296   //
1297   // These need to get fully resolved before instantiating any other
1298   // definitions that use them (e.g. Def).  However, inside a multiclass they
1299   // can't be immediately resolved so we mark them ResolveFirst to fully
1300   // resolve them later as soon as the multiclass is instantiated.
1301   bool ResolveFirst;
1302
1303   void init();
1304   void checkName();
1305
1306 public:
1307   // Constructs a record.
1308   explicit Record(Init *N, ArrayRef<SMLoc> locs, RecordKeeper &records,
1309                   bool Anonymous = false) :
1310     Name(N), Locs(locs.begin(), locs.end()), TrackedRecords(records),
1311     ID(LastID++), IsAnonymous(Anonymous), ResolveFirst(false) {
1312     init();
1313   }
1314
1315   explicit Record(StringRef N, ArrayRef<SMLoc> locs, RecordKeeper &records,
1316                   bool Anonymous = false)
1317     : Record(StringInit::get(N), locs, records, Anonymous) {}
1318
1319   // When copy-constructing a Record, we must still guarantee a globally unique
1320   // ID number.  Don't copy TheInit either since it's owned by the original
1321   // record. All other fields can be copied normally.
1322   Record(const Record &O) :
1323     Name(O.Name), Locs(O.Locs), TemplateArgs(O.TemplateArgs),
1324     Values(O.Values), SuperClasses(O.SuperClasses),
1325     TrackedRecords(O.TrackedRecords), ID(LastID++),
1326     IsAnonymous(O.IsAnonymous), ResolveFirst(O.ResolveFirst) { }
1327
1328   static unsigned getNewUID() { return LastID++; }
1329
1330   unsigned getID() const { return ID; }
1331
1332   StringRef getName() const;
1333   Init *getNameInit() const {
1334     return Name;
1335   }
1336
1337   const std::string getNameInitAsString() const {
1338     return getNameInit()->getAsUnquotedString();
1339   }
1340
1341   void setName(Init *Name);      // Also updates RecordKeeper.
1342
1343   ArrayRef<SMLoc> getLoc() const { return Locs; }
1344
1345   /// get the corresponding DefInit.
1346   DefInit *getDefInit();
1347
1348   ArrayRef<Init *> getTemplateArgs() const {
1349     return TemplateArgs;
1350   }
1351
1352   ArrayRef<RecordVal> getValues() const { return Values; }
1353
1354   ArrayRef<std::pair<Record *, SMRange>>  getSuperClasses() const {
1355     return SuperClasses;
1356   }
1357
1358   bool isTemplateArg(Init *Name) const {
1359     for (Init *TA : TemplateArgs)
1360       if (TA == Name) return true;
1361     return false;
1362   }
1363
1364   bool isTemplateArg(StringRef Name) const {
1365     return isTemplateArg(StringInit::get(Name));
1366   }
1367
1368   const RecordVal *getValue(const Init *Name) const {
1369     for (const RecordVal &Val : Values)
1370       if (Val.Name == Name) return &Val;
1371     return nullptr;
1372   }
1373
1374   const RecordVal *getValue(StringRef Name) const {
1375     return getValue(StringInit::get(Name));
1376   }
1377
1378   RecordVal *getValue(const Init *Name) {
1379     return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
1380   }
1381
1382   RecordVal *getValue(StringRef Name) {
1383     return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
1384   }
1385
1386   void addTemplateArg(Init *Name) {
1387     assert(!isTemplateArg(Name) && "Template arg already defined!");
1388     TemplateArgs.push_back(Name);
1389   }
1390
1391   void addTemplateArg(StringRef Name) {
1392     addTemplateArg(StringInit::get(Name));
1393   }
1394
1395   void addValue(const RecordVal &RV) {
1396     assert(getValue(RV.getNameInit()) == nullptr && "Value already added!");
1397     Values.push_back(RV);
1398     if (Values.size() > 1)
1399       // Keep NAME at the end of the list.  It makes record dumps a
1400       // bit prettier and allows TableGen tests to be written more
1401       // naturally.  Tests can use CHECK-NEXT to look for Record
1402       // fields they expect to see after a def.  They can't do that if
1403       // NAME is the first Record field.
1404       std::swap(Values[Values.size() - 2], Values[Values.size() - 1]);
1405   }
1406
1407   void removeValue(Init *Name) {
1408     for (unsigned i = 0, e = Values.size(); i != e; ++i)
1409       if (Values[i].getNameInit() == Name) {
1410         Values.erase(Values.begin()+i);
1411         return;
1412       }
1413     llvm_unreachable("Cannot remove an entry that does not exist!");
1414   }
1415
1416   void removeValue(StringRef Name) {
1417     removeValue(StringInit::get(Name));
1418   }
1419
1420   bool isSubClassOf(const Record *R) const {
1421     for (const auto &SCPair : SuperClasses)
1422       if (SCPair.first == R)
1423         return true;
1424     return false;
1425   }
1426
1427   bool isSubClassOf(StringRef Name) const {
1428     for (const auto &SCPair : SuperClasses) {
1429       if (const auto *SI = dyn_cast<StringInit>(SCPair.first->getNameInit())) {
1430         if (SI->getValue() == Name)
1431           return true;
1432       } else if (SCPair.first->getNameInitAsString() == Name) {
1433         return true;
1434       }
1435     }
1436     return false;
1437   }
1438
1439   void addSuperClass(Record *R, SMRange Range) {
1440     assert(!isSubClassOf(R) && "Already subclassing record!");
1441     SuperClasses.push_back(std::make_pair(R, Range));
1442   }
1443
1444   /// If there are any field references that refer to fields
1445   /// that have been filled in, we can propagate the values now.
1446   ///
1447   void resolveReferences() { resolveReferencesTo(nullptr); }
1448
1449   /// If anything in this record refers to RV, replace the
1450   /// reference to RV with the RHS of RV.  If RV is null, we resolve all
1451   /// possible references.
1452   void resolveReferencesTo(const RecordVal *RV);
1453
1454   RecordKeeper &getRecords() const {
1455     return TrackedRecords;
1456   }
1457
1458   bool isAnonymous() const {
1459     return IsAnonymous;
1460   }
1461
1462   bool isResolveFirst() const {
1463     return ResolveFirst;
1464   }
1465
1466   void setResolveFirst(bool b) {
1467     ResolveFirst = b;
1468   }
1469
1470   void print(raw_ostream &OS) const;
1471   void dump() const;
1472
1473   //===--------------------------------------------------------------------===//
1474   // High-level methods useful to tablegen back-ends
1475   //
1476
1477   /// Return the initializer for a value with the specified name,
1478   /// or throw an exception if the field does not exist.
1479   ///
1480   Init *getValueInit(StringRef FieldName) const;
1481
1482   /// Return true if the named field is unset.
1483   bool isValueUnset(StringRef FieldName) const {
1484     return isa<UnsetInit>(getValueInit(FieldName));
1485   }
1486
1487   /// This method looks up the specified field and returns
1488   /// its value as a string, throwing an exception if the field does not exist
1489   /// or if the value is not a string.
1490   ///
1491   StringRef getValueAsString(StringRef FieldName) const;
1492
1493   /// This method looks up the specified field and returns
1494   /// its value as a BitsInit, throwing an exception if the field does not exist
1495   /// or if the value is not the right type.
1496   ///
1497   BitsInit *getValueAsBitsInit(StringRef FieldName) const;
1498
1499   /// This method looks up the specified field and returns
1500   /// its value as a ListInit, throwing an exception if the field does not exist
1501   /// or if the value is not the right type.
1502   ///
1503   ListInit *getValueAsListInit(StringRef FieldName) const;
1504
1505   /// This method looks up the specified field and
1506   /// returns its value as a vector of records, throwing an exception if the
1507   /// field does not exist or if the value is not the right type.
1508   ///
1509   std::vector<Record*> getValueAsListOfDefs(StringRef FieldName) const;
1510
1511   /// This method looks up the specified field and
1512   /// returns its value as a vector of integers, throwing an exception if the
1513   /// field does not exist or if the value is not the right type.
1514   ///
1515   std::vector<int64_t> getValueAsListOfInts(StringRef FieldName) const;
1516
1517   /// This method looks up the specified field and
1518   /// returns its value as a vector of strings, throwing an exception if the
1519   /// field does not exist or if the value is not the right type.
1520   ///
1521   std::vector<StringRef> getValueAsListOfStrings(StringRef FieldName) const;
1522
1523   /// This method looks up the specified field and returns its
1524   /// value as a Record, throwing an exception if the field does not exist or if
1525   /// the value is not the right type.
1526   ///
1527   Record *getValueAsDef(StringRef FieldName) const;
1528
1529   /// This method looks up the specified field and returns its
1530   /// value as a bit, throwing an exception if the field does not exist or if
1531   /// the value is not the right type.
1532   ///
1533   bool getValueAsBit(StringRef FieldName) const;
1534
1535   /// This method looks up the specified field and
1536   /// returns its value as a bit. If the field is unset, sets Unset to true and
1537   /// returns false.
1538   ///
1539   bool getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const;
1540
1541   /// This method looks up the specified field and returns its
1542   /// value as an int64_t, throwing an exception if the field does not exist or
1543   /// if the value is not the right type.
1544   ///
1545   int64_t getValueAsInt(StringRef FieldName) const;
1546
1547   /// This method looks up the specified field and returns its
1548   /// value as an Dag, throwing an exception if the field does not exist or if
1549   /// the value is not the right type.
1550   ///
1551   DagInit *getValueAsDag(StringRef FieldName) const;
1552 };
1553
1554 raw_ostream &operator<<(raw_ostream &OS, const Record &R);
1555
1556 struct MultiClass {
1557   Record Rec;  // Placeholder for template args and Name.
1558   typedef std::vector<std::unique_ptr<Record>> RecordVector;
1559   RecordVector DefPrototypes;
1560
1561   void dump() const;
1562
1563   MultiClass(StringRef Name, SMLoc Loc, RecordKeeper &Records) :
1564     Rec(Name, Loc, Records) {}
1565 };
1566
1567 class RecordKeeper {
1568   typedef std::map<std::string, std::unique_ptr<Record>> RecordMap;
1569   RecordMap Classes, Defs;
1570
1571 public:
1572   const RecordMap &getClasses() const { return Classes; }
1573   const RecordMap &getDefs() const { return Defs; }
1574
1575   Record *getClass(StringRef Name) const {
1576     auto I = Classes.find(Name);
1577     return I == Classes.end() ? nullptr : I->second.get();
1578   }
1579
1580   Record *getDef(StringRef Name) const {
1581     auto I = Defs.find(Name);
1582     return I == Defs.end() ? nullptr : I->second.get();
1583   }
1584
1585   void addClass(std::unique_ptr<Record> R) {
1586     bool Ins = Classes.insert(std::make_pair(R->getName(),
1587                                              std::move(R))).second;
1588     (void)Ins;
1589     assert(Ins && "Class already exists");
1590   }
1591
1592   void addDef(std::unique_ptr<Record> R) {
1593     bool Ins = Defs.insert(std::make_pair(R->getName(),
1594                                           std::move(R))).second;
1595     (void)Ins;
1596     assert(Ins && "Record already exists");
1597   }
1598
1599   //===--------------------------------------------------------------------===//
1600   // High-level helper methods, useful for tablegen backends...
1601
1602   /// This method returns all concrete definitions
1603   /// that derive from the specified class name.  A class with the specified
1604   /// name must exist.
1605   std::vector<Record *> getAllDerivedDefinitions(StringRef ClassName) const;
1606
1607   void dump() const;
1608 };
1609
1610 /// Sorting predicate to sort record pointers by name.
1611 ///
1612 struct LessRecord {
1613   bool operator()(const Record *Rec1, const Record *Rec2) const {
1614     return StringRef(Rec1->getName()).compare_numeric(Rec2->getName()) < 0;
1615   }
1616 };
1617
1618 /// Sorting predicate to sort record pointers by their
1619 /// unique ID. If you just need a deterministic order, use this, since it
1620 /// just compares two `unsigned`; the other sorting predicates require
1621 /// string manipulation.
1622 struct LessRecordByID {
1623   bool operator()(const Record *LHS, const Record *RHS) const {
1624     return LHS->getID() < RHS->getID();
1625   }
1626 };
1627
1628 /// Sorting predicate to sort record pointers by their
1629 /// name field.
1630 ///
1631 struct LessRecordFieldName {
1632   bool operator()(const Record *Rec1, const Record *Rec2) const {
1633     return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name");
1634   }
1635 };
1636
1637 struct LessRecordRegister {
1638   static bool ascii_isdigit(char x) { return x >= '0' && x <= '9'; }
1639
1640   struct RecordParts {
1641     SmallVector<std::pair< bool, StringRef>, 4> Parts;
1642
1643     RecordParts(StringRef Rec) {
1644       if (Rec.empty())
1645         return;
1646
1647       size_t Len = 0;
1648       const char *Start = Rec.data();
1649       const char *Curr = Start;
1650       bool isDigitPart = ascii_isdigit(Curr[0]);
1651       for (size_t I = 0, E = Rec.size(); I != E; ++I, ++Len) {
1652         bool isDigit = ascii_isdigit(Curr[I]);
1653         if (isDigit != isDigitPart) {
1654           Parts.push_back(std::make_pair(isDigitPart, StringRef(Start, Len)));
1655           Len = 0;
1656           Start = &Curr[I];
1657           isDigitPart = ascii_isdigit(Curr[I]);
1658         }
1659       }
1660       // Push the last part.
1661       Parts.push_back(std::make_pair(isDigitPart, StringRef(Start, Len)));
1662     }
1663
1664     size_t size() { return Parts.size(); }
1665
1666     std::pair<bool, StringRef> getPart(size_t i) {
1667       assert (i < Parts.size() && "Invalid idx!");
1668       return Parts[i];
1669     }
1670   };
1671
1672   bool operator()(const Record *Rec1, const Record *Rec2) const {
1673     RecordParts LHSParts(StringRef(Rec1->getName()));
1674     RecordParts RHSParts(StringRef(Rec2->getName()));
1675
1676     size_t LHSNumParts = LHSParts.size();
1677     size_t RHSNumParts = RHSParts.size();
1678     assert (LHSNumParts && RHSNumParts && "Expected at least one part!");
1679
1680     if (LHSNumParts != RHSNumParts)
1681       return LHSNumParts < RHSNumParts;
1682
1683     // We expect the registers to be of the form [_a-zA-z]+([0-9]*[_a-zA-Z]*)*.
1684     for (size_t I = 0, E = LHSNumParts; I < E; I+=2) {
1685       std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
1686       std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
1687       // Expect even part to always be alpha.
1688       assert (LHSPart.first == false && RHSPart.first == false &&
1689               "Expected both parts to be alpha.");
1690       if (int Res = LHSPart.second.compare(RHSPart.second))
1691         return Res < 0;
1692     }
1693     for (size_t I = 1, E = LHSNumParts; I < E; I+=2) {
1694       std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
1695       std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
1696       // Expect odd part to always be numeric.
1697       assert (LHSPart.first == true && RHSPart.first == true &&
1698               "Expected both parts to be numeric.");
1699       if (LHSPart.second.size() != RHSPart.second.size())
1700         return LHSPart.second.size() < RHSPart.second.size();
1701
1702       unsigned LHSVal, RHSVal;
1703
1704       bool LHSFailed = LHSPart.second.getAsInteger(10, LHSVal); (void)LHSFailed;
1705       assert(!LHSFailed && "Unable to convert LHS to integer.");
1706       bool RHSFailed = RHSPart.second.getAsInteger(10, RHSVal); (void)RHSFailed;
1707       assert(!RHSFailed && "Unable to convert RHS to integer.");
1708
1709       if (LHSVal != RHSVal)
1710         return LHSVal < RHSVal;
1711     }
1712     return LHSNumParts < RHSNumParts;
1713   }
1714 };
1715
1716 raw_ostream &operator<<(raw_ostream &OS, const RecordKeeper &RK);
1717
1718 /// Return an Init with a qualifier prefix referring
1719 /// to CurRec's name.
1720 Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1721                   Init *Name, StringRef Scoper);
1722
1723 } // end namespace llvm
1724
1725 #endif // LLVM_TABLEGEN_RECORD_H