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