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