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