c248370de174df2d47e517a0ee178a9e86eaa90b
[oota-llvm.git] / lib / TableGen / Record.cpp
1 //===- Record.cpp - Record implementation ---------------------------------===//
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 // Implement the tablegen record classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/TableGen/Record.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/FoldingSet.h"
17 #include "llvm/ADT/Hashing.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/Support/DataTypes.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/Format.h"
25 #include "llvm/TableGen/Error.h"
26
27 using namespace llvm;
28
29 //===----------------------------------------------------------------------===//
30 //    std::string wrapper for DenseMap purposes
31 //===----------------------------------------------------------------------===//
32
33 namespace llvm {
34
35 /// TableGenStringKey - This is a wrapper for std::string suitable for
36 /// using as a key to a DenseMap.  Because there isn't a particularly
37 /// good way to indicate tombstone or empty keys for strings, we want
38 /// to wrap std::string to indicate that this is a "special" string
39 /// not expected to take on certain values (those of the tombstone and
40 /// empty keys).  This makes things a little safer as it clarifies
41 /// that DenseMap is really not appropriate for general strings.
42
43 class TableGenStringKey {
44 public:
45   TableGenStringKey(const std::string &str) : data(str) {}
46   TableGenStringKey(const char *str) : data(str) {}
47
48   const std::string &str() const { return data; }
49
50   friend hash_code hash_value(const TableGenStringKey &Value) {
51     using llvm::hash_value;
52     return hash_value(Value.str());
53   }
54 private:
55   std::string data;
56 };
57
58 /// Specialize DenseMapInfo for TableGenStringKey.
59 template<> struct DenseMapInfo<TableGenStringKey> {
60   static inline TableGenStringKey getEmptyKey() {
61     TableGenStringKey Empty("<<<EMPTY KEY>>>");
62     return Empty;
63   }
64   static inline TableGenStringKey getTombstoneKey() {
65     TableGenStringKey Tombstone("<<<TOMBSTONE KEY>>>");
66     return Tombstone;
67   }
68   static unsigned getHashValue(const TableGenStringKey& Val) {
69     using llvm::hash_value;
70     return hash_value(Val);
71   }
72   static bool isEqual(const TableGenStringKey& LHS,
73                       const TableGenStringKey& RHS) {
74     return LHS.str() == RHS.str();
75   }
76 };
77
78 } // namespace llvm
79
80 //===----------------------------------------------------------------------===//
81 //    Type implementations
82 //===----------------------------------------------------------------------===//
83
84 BitRecTy BitRecTy::Shared;
85 IntRecTy IntRecTy::Shared;
86 StringRecTy StringRecTy::Shared;
87 DagRecTy DagRecTy::Shared;
88
89 void RecTy::anchor() { }
90 void RecTy::dump() const { print(errs()); }
91
92 ListRecTy *RecTy::getListTy() {
93   if (!ListTy)
94     ListTy.reset(new ListRecTy(this));
95   return ListTy.get();
96 }
97
98 bool RecTy::baseClassOf(const RecTy *RHS) const{
99   assert (RHS && "NULL pointer");
100   return Kind == RHS->getRecTyKind();
101 }
102
103 Init *BitRecTy::convertValue(BitsInit *BI) {
104   if (BI->getNumBits() != 1) return nullptr; // Only accept if just one bit!
105   return BI->getBit(0);
106 }
107
108 Init *BitRecTy::convertValue(IntInit *II) {
109   int64_t Val = II->getValue();
110   if (Val != 0 && Val != 1) return nullptr;  // Only accept 0 or 1 for a bit!
111
112   return BitInit::get(Val != 0);
113 }
114
115 Init *BitRecTy::convertValue(TypedInit *VI) {
116   RecTy *Ty = VI->getType();
117   if (isa<BitRecTy>(Ty))
118     return VI;  // Accept variable if it is already of bit type!
119   if (auto *BitsTy = dyn_cast<BitsRecTy>(Ty))
120     // Accept only bits<1> expression.
121     return BitsTy->getNumBits() == 1 ? VI : nullptr;
122   // Ternary !if can be converted to bit, but only if both sides are
123   // convertible to a bit.
124   if (TernOpInit *TOI = dyn_cast<TernOpInit>(VI)) {
125     if (TOI->getOpcode() != TernOpInit::TernaryOp::IF)
126       return nullptr;
127     if (!TOI->getMHS()->convertInitializerTo(BitRecTy::get()) ||
128         !TOI->getRHS()->convertInitializerTo(BitRecTy::get()))
129       return nullptr;
130     return TOI;
131   }
132   return nullptr;
133 }
134
135 bool BitRecTy::baseClassOf(const RecTy *RHS) const{
136   if(RecTy::baseClassOf(RHS) || RHS->getRecTyKind() == IntRecTyKind)
137     return true;
138   if(const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
139     return BitsTy->getNumBits() == 1;
140   return false;
141 }
142
143 BitsRecTy *BitsRecTy::get(unsigned Sz) {
144   static std::vector<std::unique_ptr<BitsRecTy>> Shared;
145   if (Sz >= Shared.size())
146     Shared.resize(Sz + 1);
147   std::unique_ptr<BitsRecTy> &Ty = Shared[Sz];
148   if (!Ty)
149     Ty.reset(new BitsRecTy(Sz));
150   return Ty.get();
151 }
152
153 std::string BitsRecTy::getAsString() const {
154   return "bits<" + utostr(Size) + ">";
155 }
156
157 Init *BitsRecTy::convertValue(UnsetInit *UI) {
158   SmallVector<Init *, 16> NewBits(Size);
159
160   for (unsigned i = 0; i != Size; ++i)
161     NewBits[i] = UnsetInit::get();
162
163   return BitsInit::get(NewBits);
164 }
165
166 Init *BitsRecTy::convertValue(BitInit *UI) {
167   if (Size != 1) return nullptr;  // Can only convert single bit.
168   return BitsInit::get(UI);
169 }
170
171 /// canFitInBitfield - Return true if the number of bits is large enough to hold
172 /// the integer value.
173 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
174   // For example, with NumBits == 4, we permit Values from [-7 .. 15].
175   return (NumBits >= sizeof(Value) * 8) ||
176          (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
177 }
178
179 /// convertValue from Int initializer to bits type: Split the integer up into the
180 /// appropriate bits.
181 ///
182 Init *BitsRecTy::convertValue(IntInit *II) {
183   int64_t Value = II->getValue();
184   // Make sure this bitfield is large enough to hold the integer value.
185   if (!canFitInBitfield(Value, Size))
186     return nullptr;
187
188   SmallVector<Init *, 16> NewBits(Size);
189
190   for (unsigned i = 0; i != Size; ++i)
191     NewBits[i] = BitInit::get(Value & (1LL << i));
192
193   return BitsInit::get(NewBits);
194 }
195
196 Init *BitsRecTy::convertValue(BitsInit *BI) {
197   // If the number of bits is right, return it.  Otherwise we need to expand or
198   // truncate.
199   if (BI->getNumBits() == Size) return BI;
200   return nullptr;
201 }
202
203 Init *BitsRecTy::convertValue(TypedInit *VI) {
204   if (Size == 1 && isa<BitRecTy>(VI->getType()))
205     return BitsInit::get(VI);
206
207   if (VI->getType()->typeIsConvertibleTo(this)) {
208     SmallVector<Init *, 16> NewBits(Size);
209
210     for (unsigned i = 0; i != Size; ++i)
211       NewBits[i] = VarBitInit::get(VI, i);
212     return BitsInit::get(NewBits);
213   }
214
215   return nullptr;
216 }
217
218 bool BitsRecTy::baseClassOf(const RecTy *RHS) const{
219   if (RecTy::baseClassOf(RHS)) //argument and the receiver are the same type
220     return cast<BitsRecTy>(RHS)->Size == Size;
221   RecTyKind kind = RHS->getRecTyKind();
222   return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
223 }
224
225 Init *IntRecTy::convertValue(BitInit *BI) {
226   return IntInit::get(BI->getValue());
227 }
228
229 Init *IntRecTy::convertValue(BitsInit *BI) {
230   int64_t Result = 0;
231   for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
232     if (BitInit *Bit = dyn_cast<BitInit>(BI->getBit(i))) {
233       Result |= Bit->getValue() << i;
234     } else {
235       return nullptr;
236     }
237   return IntInit::get(Result);
238 }
239
240 Init *IntRecTy::convertValue(TypedInit *TI) {
241   if (TI->getType()->typeIsConvertibleTo(this))
242     return TI;  // Accept variable if already of the right type!
243   return nullptr;
244 }
245
246 bool IntRecTy::baseClassOf(const RecTy *RHS) const{
247   RecTyKind kind = RHS->getRecTyKind();
248   return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
249 }
250
251 Init *StringRecTy::convertValue(UnOpInit *BO) {
252   if (BO->getOpcode() == UnOpInit::CAST) {
253     Init *L = BO->getOperand()->convertInitializerTo(this);
254     if (!L) return nullptr;
255     if (L != BO->getOperand())
256       return UnOpInit::get(UnOpInit::CAST, L, StringRecTy::get());
257     return BO;
258   }
259
260   return convertValue((TypedInit*)BO);
261 }
262
263 Init *StringRecTy::convertValue(BinOpInit *BO) {
264   if (BO->getOpcode() == BinOpInit::STRCONCAT) {
265     Init *L = BO->getLHS()->convertInitializerTo(this);
266     Init *R = BO->getRHS()->convertInitializerTo(this);
267     if (!L || !R) return nullptr;
268     if (L != BO->getLHS() || R != BO->getRHS())
269       return BinOpInit::get(BinOpInit::STRCONCAT, L, R, StringRecTy::get());
270     return BO;
271   }
272
273   return convertValue((TypedInit*)BO);
274 }
275
276
277 Init *StringRecTy::convertValue(TypedInit *TI) {
278   if (isa<StringRecTy>(TI->getType()))
279     return TI;  // Accept variable if already of the right type!
280   return nullptr;
281 }
282
283 std::string ListRecTy::getAsString() const {
284   return "list<" + Ty->getAsString() + ">";
285 }
286
287 Init *ListRecTy::convertValue(ListInit *LI) {
288   std::vector<Init*> Elements;
289
290   // Verify that all of the elements of the list are subclasses of the
291   // appropriate class!
292   for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
293     if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
294       Elements.push_back(CI);
295     else
296       return nullptr;
297
298   if (!isa<ListRecTy>(LI->getType()))
299     return nullptr;
300
301   return ListInit::get(Elements, this);
302 }
303
304 Init *ListRecTy::convertValue(TypedInit *TI) {
305   // Ensure that TI is compatible with our class.
306   if (ListRecTy *LRT = dyn_cast<ListRecTy>(TI->getType()))
307     if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
308       return TI;
309   return nullptr;
310 }
311
312 bool ListRecTy::baseClassOf(const RecTy *RHS) const{
313   if(const ListRecTy* ListTy = dyn_cast<ListRecTy>(RHS))
314     return ListTy->getElementType()->typeIsConvertibleTo(Ty);
315   return false;
316 }
317
318 Init *DagRecTy::convertValue(TypedInit *TI) {
319   if (TI->getType()->typeIsConvertibleTo(this))
320     return TI;
321   return nullptr;
322 }
323
324 Init *DagRecTy::convertValue(UnOpInit *BO) {
325   if (BO->getOpcode() == UnOpInit::CAST) {
326     Init *L = BO->getOperand()->convertInitializerTo(this);
327     if (!L) return nullptr;
328     if (L != BO->getOperand())
329       return UnOpInit::get(UnOpInit::CAST, L, new DagRecTy);
330     return BO;
331   }
332   return nullptr;
333 }
334
335 Init *DagRecTy::convertValue(BinOpInit *BO) {
336   if (BO->getOpcode() == BinOpInit::CONCAT) {
337     Init *L = BO->getLHS()->convertInitializerTo(this);
338     Init *R = BO->getRHS()->convertInitializerTo(this);
339     if (!L || !R) return nullptr;
340     if (L != BO->getLHS() || R != BO->getRHS())
341       return BinOpInit::get(BinOpInit::CONCAT, L, R, new DagRecTy);
342     return BO;
343   }
344   return nullptr;
345 }
346
347 RecordRecTy *RecordRecTy::get(Record *R) {
348   return dyn_cast<RecordRecTy>(R->getDefInit()->getType());
349 }
350
351 std::string RecordRecTy::getAsString() const {
352   return Rec->getName();
353 }
354
355 Init *RecordRecTy::convertValue(DefInit *DI) {
356   // Ensure that DI is a subclass of Rec.
357   if (!DI->getDef()->isSubClassOf(Rec))
358     return nullptr;
359   return DI;
360 }
361
362 Init *RecordRecTy::convertValue(TypedInit *TI) {
363   // Ensure that TI is compatible with Rec.
364   if (RecordRecTy *RRT = dyn_cast<RecordRecTy>(TI->getType()))
365     if (RRT->getRecord()->isSubClassOf(getRecord()) ||
366         RRT->getRecord() == getRecord())
367       return TI;
368   return nullptr;
369 }
370
371 bool RecordRecTy::baseClassOf(const RecTy *RHS) const{
372   const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
373   if (!RTy)
374     return false;
375
376   if (Rec == RTy->getRecord() || RTy->getRecord()->isSubClassOf(Rec))
377     return true;
378
379   const std::vector<Record*> &SC = Rec->getSuperClasses();
380   for (unsigned i = 0, e = SC.size(); i != e; ++i)
381     if (RTy->getRecord()->isSubClassOf(SC[i]))
382       return true;
383
384   return false;
385 }
386
387 /// resolveTypes - Find a common type that T1 and T2 convert to.
388 /// Return null if no such type exists.
389 ///
390 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
391   if (T1->typeIsConvertibleTo(T2))
392     return T2;
393   if (T2->typeIsConvertibleTo(T1))
394     return T1;
395
396   // If one is a Record type, check superclasses
397   if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
398     // See if T2 inherits from a type T1 also inherits from
399     for (Record *SuperRec1 : RecTy1->getRecord()->getSuperClasses()) {
400       RecordRecTy *SuperRecTy1 = RecordRecTy::get(SuperRec1);
401       RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
402       if (NewType1)
403         return NewType1;
404     }
405   }
406   if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) {
407     // See if T1 inherits from a type T2 also inherits from
408     for (Record *SuperRec2 : RecTy2->getRecord()->getSuperClasses()) {
409       RecordRecTy *SuperRecTy2 = RecordRecTy::get(SuperRec2);
410       RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
411       if (NewType2)
412         return NewType2;
413     }
414   }
415   return nullptr;
416 }
417
418
419 //===----------------------------------------------------------------------===//
420 //    Initializer implementations
421 //===----------------------------------------------------------------------===//
422
423 void Init::anchor() { }
424 void Init::dump() const { return print(errs()); }
425
426 void UnsetInit::anchor() { }
427
428 UnsetInit *UnsetInit::get() {
429   static UnsetInit TheInit;
430   return &TheInit;
431 }
432
433 void BitInit::anchor() { }
434
435 BitInit *BitInit::get(bool V) {
436   static BitInit True(true);
437   static BitInit False(false);
438
439   return V ? &True : &False;
440 }
441
442 static void
443 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
444   ID.AddInteger(Range.size());
445
446   for (Init *I : Range)
447     ID.AddPointer(I);
448 }
449
450 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
451   static FoldingSet<BitsInit> ThePool;
452   static std::vector<std::unique_ptr<BitsInit>> TheActualPool;
453
454   FoldingSetNodeID ID;
455   ProfileBitsInit(ID, Range);
456
457   void *IP = nullptr;
458   if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
459     return I;
460
461   BitsInit *I = new BitsInit(Range);
462   ThePool.InsertNode(I, IP);
463   TheActualPool.push_back(std::unique_ptr<BitsInit>(I));
464   return I;
465 }
466
467 void BitsInit::Profile(FoldingSetNodeID &ID) const {
468   ProfileBitsInit(ID, Bits);
469 }
470
471 Init *
472 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
473   SmallVector<Init *, 16> NewBits(Bits.size());
474
475   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
476     if (Bits[i] >= getNumBits())
477       return nullptr;
478     NewBits[i] = getBit(Bits[i]);
479   }
480   return BitsInit::get(NewBits);
481 }
482
483 std::string BitsInit::getAsString() const {
484   std::string Result = "{ ";
485   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
486     if (i) Result += ", ";
487     if (Init *Bit = getBit(e-i-1))
488       Result += Bit->getAsString();
489     else
490       Result += "*";
491   }
492   return Result + " }";
493 }
494
495 // Fix bit initializer to preserve the behavior that bit reference from a unset
496 // bits initializer will resolve into VarBitInit to keep the field name and bit
497 // number used in targets with fixed insn length.
498 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
499   if (RV || !isa<UnsetInit>(After))
500     return After;
501   return Before;
502 }
503
504 // resolveReferences - If there are any field references that refer to fields
505 // that have been filled in, we can propagate the values now.
506 //
507 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
508   bool Changed = false;
509   SmallVector<Init *, 16> NewBits(getNumBits());
510
511   Init *CachedInit = nullptr;
512   Init *CachedBitVar = nullptr;
513   bool CachedBitVarChanged = false;
514
515   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
516     Init *CurBit = Bits[i];
517     Init *CurBitVar = CurBit->getBitVar();
518
519     NewBits[i] = CurBit;
520
521     if (CurBitVar == CachedBitVar) {
522       if (CachedBitVarChanged) {
523         Init *Bit = CachedInit->getBit(CurBit->getBitNum());
524         NewBits[i] = fixBitInit(RV, CurBit, Bit);
525       }
526       continue;
527     }
528     CachedBitVar = CurBitVar;
529     CachedBitVarChanged = false;
530
531     Init *B;
532     do {
533       B = CurBitVar;
534       CurBitVar = CurBitVar->resolveReferences(R, RV);
535       CachedBitVarChanged |= B != CurBitVar;
536       Changed |= B != CurBitVar;
537     } while (B != CurBitVar);
538     CachedInit = CurBitVar;
539
540     if (CachedBitVarChanged) {
541       Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
542       NewBits[i] = fixBitInit(RV, CurBit, Bit);
543     }
544   }
545
546   if (Changed)
547     return BitsInit::get(NewBits);
548
549   return const_cast<BitsInit *>(this);
550 }
551
552 IntInit *IntInit::get(int64_t V) {
553   static DenseMap<int64_t, std::unique_ptr<IntInit>> ThePool;
554
555   std::unique_ptr<IntInit> &I = ThePool[V];
556   if (!I) I.reset(new IntInit(V));
557   return I.get();
558 }
559
560 std::string IntInit::getAsString() const {
561   return itostr(Value);
562 }
563
564 Init *
565 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
566   SmallVector<Init *, 16> NewBits(Bits.size());
567
568   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
569     if (Bits[i] >= 64)
570       return nullptr;
571
572     NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
573   }
574   return BitsInit::get(NewBits);
575 }
576
577 void StringInit::anchor() { }
578
579 StringInit *StringInit::get(StringRef V) {
580   static StringMap<std::unique_ptr<StringInit>> ThePool;
581
582   std::unique_ptr<StringInit> &I = ThePool[V];
583   if (!I) I.reset(new StringInit(V));
584   return I.get();
585 }
586
587 static void ProfileListInit(FoldingSetNodeID &ID,
588                             ArrayRef<Init *> Range,
589                             RecTy *EltTy) {
590   ID.AddInteger(Range.size());
591   ID.AddPointer(EltTy);
592
593   for (Init *I : Range)
594     ID.AddPointer(I);
595 }
596
597 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
598   static FoldingSet<ListInit> ThePool;
599   static std::vector<std::unique_ptr<ListInit>> TheActualPool;
600
601   FoldingSetNodeID ID;
602   ProfileListInit(ID, Range, EltTy);
603
604   void *IP = nullptr;
605   if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
606     return I;
607
608   ListInit *I = new ListInit(Range, EltTy);
609   ThePool.InsertNode(I, IP);
610   TheActualPool.push_back(std::unique_ptr<ListInit>(I));
611   return I;
612 }
613
614 void ListInit::Profile(FoldingSetNodeID &ID) const {
615   RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
616
617   ProfileListInit(ID, Values, EltTy);
618 }
619
620 Init *
621 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
622   std::vector<Init*> Vals;
623   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
624     if (Elements[i] >= getSize())
625       return nullptr;
626     Vals.push_back(getElement(Elements[i]));
627   }
628   return ListInit::get(Vals, getType());
629 }
630
631 Record *ListInit::getElementAsRecord(unsigned i) const {
632   assert(i < Values.size() && "List element index out of range!");
633   DefInit *DI = dyn_cast<DefInit>(Values[i]);
634   if (!DI)
635     PrintFatalError("Expected record in list!");
636   return DI->getDef();
637 }
638
639 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
640   std::vector<Init*> Resolved;
641   Resolved.reserve(getSize());
642   bool Changed = false;
643
644   for (unsigned i = 0, e = getSize(); i != e; ++i) {
645     Init *E;
646     Init *CurElt = getElement(i);
647
648     do {
649       E = CurElt;
650       CurElt = CurElt->resolveReferences(R, RV);
651       Changed |= E != CurElt;
652     } while (E != CurElt);
653     Resolved.push_back(E);
654   }
655
656   if (Changed)
657     return ListInit::get(Resolved, getType());
658   return const_cast<ListInit *>(this);
659 }
660
661 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
662                                             unsigned Elt) const {
663   if (Elt >= getSize())
664     return nullptr;  // Out of range reference.
665   Init *E = getElement(Elt);
666   // If the element is set to some value, or if we are resolving a reference
667   // to a specific variable and that variable is explicitly unset, then
668   // replace the VarListElementInit with it.
669   if (IRV || !isa<UnsetInit>(E))
670     return E;
671   return nullptr;
672 }
673
674 std::string ListInit::getAsString() const {
675   std::string Result = "[";
676   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
677     if (i) Result += ", ";
678     Result += Values[i]->getAsString();
679   }
680   return Result + "]";
681 }
682
683 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
684                                           unsigned Elt) const {
685   Init *Resolved = resolveReferences(R, IRV);
686   OpInit *OResolved = dyn_cast<OpInit>(Resolved);
687   if (OResolved) {
688     Resolved = OResolved->Fold(&R, nullptr);
689   }
690
691   if (Resolved != this) {
692     TypedInit *Typed = cast<TypedInit>(Resolved);
693     if (Init *New = Typed->resolveListElementReference(R, IRV, Elt))
694       return New;
695     return VarListElementInit::get(Typed, Elt);
696   }
697
698   return nullptr;
699 }
700
701 Init *OpInit::getBit(unsigned Bit) const {
702   if (getType() == BitRecTy::get())
703     return const_cast<OpInit*>(this);
704   return VarBitInit::get(const_cast<OpInit*>(this), Bit);
705 }
706
707 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
708   typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
709   static DenseMap<Key, std::unique_ptr<UnOpInit>> ThePool;
710
711   Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
712
713   std::unique_ptr<UnOpInit> &I = ThePool[TheKey];
714   if (!I) I.reset(new UnOpInit(opc, lhs, Type));
715   return I.get();
716 }
717
718 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
719   switch (getOpcode()) {
720   case CAST: {
721     if (getType()->getAsString() == "string") {
722       if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
723         return LHSs;
724
725       if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
726         return StringInit::get(LHSd->getDef()->getName());
727
728       if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
729         return StringInit::get(LHSi->getAsString());
730     } else {
731       if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
732         std::string Name = LHSs->getValue();
733
734         // From TGParser::ParseIDValue
735         if (CurRec) {
736           if (const RecordVal *RV = CurRec->getValue(Name)) {
737             if (RV->getType() != getType())
738               PrintFatalError("type mismatch in cast");
739             return VarInit::get(Name, RV->getType());
740           }
741
742           Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
743                                               ":");
744       
745           if (CurRec->isTemplateArg(TemplateArgName)) {
746             const RecordVal *RV = CurRec->getValue(TemplateArgName);
747             assert(RV && "Template arg doesn't exist??");
748
749             if (RV->getType() != getType())
750               PrintFatalError("type mismatch in cast");
751
752             return VarInit::get(TemplateArgName, RV->getType());
753           }
754         }
755
756         if (CurMultiClass) {
757           Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
758
759           if (CurMultiClass->Rec.isTemplateArg(MCName)) {
760             const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
761             assert(RV && "Template arg doesn't exist??");
762
763             if (RV->getType() != getType())
764               PrintFatalError("type mismatch in cast");
765
766             return VarInit::get(MCName, RV->getType());
767           }
768         }
769         assert(CurRec && "NULL pointer");
770         if (Record *D = (CurRec->getRecords()).getDef(Name))
771           return DefInit::get(D);
772
773         PrintFatalError(CurRec->getLoc(),
774                         "Undefined reference:'" + Name + "'\n");
775       }
776     }
777     break;
778   }
779   case HEAD: {
780     if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
781       assert(LHSl->getSize() != 0 && "Empty list in car");
782       return LHSl->getElement(0);
783     }
784     break;
785   }
786   case TAIL: {
787     if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
788       assert(LHSl->getSize() != 0 && "Empty list in cdr");
789       // Note the +1.  We can't just pass the result of getValues()
790       // directly.
791       ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
792       ArrayRef<Init *>::iterator end   = LHSl->getValues().end();
793       ListInit *Result =
794         ListInit::get(ArrayRef<Init *>(begin, end - begin),
795                       LHSl->getType());
796       return Result;
797     }
798     break;
799   }
800   case EMPTY: {
801     if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
802       if (LHSl->getSize() == 0) {
803         return IntInit::get(1);
804       } else {
805         return IntInit::get(0);
806       }
807     }
808     if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
809       if (LHSs->getValue().empty()) {
810         return IntInit::get(1);
811       } else {
812         return IntInit::get(0);
813       }
814     }
815
816     break;
817   }
818   }
819   return const_cast<UnOpInit *>(this);
820 }
821
822 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
823   Init *lhs = LHS->resolveReferences(R, RV);
824
825   if (LHS != lhs)
826     return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, nullptr);
827   return Fold(&R, nullptr);
828 }
829
830 std::string UnOpInit::getAsString() const {
831   std::string Result;
832   switch (Opc) {
833   case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
834   case HEAD: Result = "!head"; break;
835   case TAIL: Result = "!tail"; break;
836   case EMPTY: Result = "!empty"; break;
837   }
838   return Result + "(" + LHS->getAsString() + ")";
839 }
840
841 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
842                           Init *rhs, RecTy *Type) {
843   typedef std::pair<
844     std::pair<std::pair<unsigned, Init *>, Init *>,
845     RecTy *
846     > Key;
847
848   static DenseMap<Key, std::unique_ptr<BinOpInit>> ThePool;
849
850   Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
851                             Type));
852
853   std::unique_ptr<BinOpInit> &I = ThePool[TheKey];
854   if (!I) I.reset(new BinOpInit(opc, lhs, rhs, Type));
855   return I.get();
856 }
857
858 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
859   switch (getOpcode()) {
860   case CONCAT: {
861     DagInit *LHSs = dyn_cast<DagInit>(LHS);
862     DagInit *RHSs = dyn_cast<DagInit>(RHS);
863     if (LHSs && RHSs) {
864       DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
865       DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
866       if (!LOp || !ROp || LOp->getDef() != ROp->getDef())
867         PrintFatalError("Concated Dag operators do not match!");
868       std::vector<Init*> Args;
869       std::vector<std::string> ArgNames;
870       for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
871         Args.push_back(LHSs->getArg(i));
872         ArgNames.push_back(LHSs->getArgName(i));
873       }
874       for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
875         Args.push_back(RHSs->getArg(i));
876         ArgNames.push_back(RHSs->getArgName(i));
877       }
878       return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
879     }
880     break;
881   }
882   case LISTCONCAT: {
883     ListInit *LHSs = dyn_cast<ListInit>(LHS);
884     ListInit *RHSs = dyn_cast<ListInit>(RHS);
885     if (LHSs && RHSs) {
886       std::vector<Init *> Args;
887       Args.insert(Args.end(), LHSs->begin(), LHSs->end());
888       Args.insert(Args.end(), RHSs->begin(), RHSs->end());
889       return ListInit::get(
890           Args, static_cast<ListRecTy *>(LHSs->getType())->getElementType());
891     }
892     break;
893   }
894   case STRCONCAT: {
895     StringInit *LHSs = dyn_cast<StringInit>(LHS);
896     StringInit *RHSs = dyn_cast<StringInit>(RHS);
897     if (LHSs && RHSs)
898       return StringInit::get(LHSs->getValue() + RHSs->getValue());
899     break;
900   }
901   case EQ: {
902     // try to fold eq comparison for 'bit' and 'int', otherwise fallback
903     // to string objects.
904     IntInit *L =
905       dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
906     IntInit *R =
907       dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
908
909     if (L && R)
910       return IntInit::get(L->getValue() == R->getValue());
911
912     StringInit *LHSs = dyn_cast<StringInit>(LHS);
913     StringInit *RHSs = dyn_cast<StringInit>(RHS);
914
915     // Make sure we've resolved
916     if (LHSs && RHSs)
917       return IntInit::get(LHSs->getValue() == RHSs->getValue());
918
919     break;
920   }
921   case ADD:
922   case AND:
923   case SHL:
924   case SRA:
925   case SRL: {
926     IntInit *LHSi =
927       dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
928     IntInit *RHSi =
929       dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
930     if (LHSi && RHSi) {
931       int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
932       int64_t Result;
933       switch (getOpcode()) {
934       default: llvm_unreachable("Bad opcode!");
935       case ADD: Result = LHSv +  RHSv; break;
936       case AND: Result = LHSv &  RHSv; break;
937       case SHL: Result = LHSv << RHSv; break;
938       case SRA: Result = LHSv >> RHSv; break;
939       case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
940       }
941       return IntInit::get(Result);
942     }
943     break;
944   }
945   }
946   return const_cast<BinOpInit *>(this);
947 }
948
949 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
950   Init *lhs = LHS->resolveReferences(R, RV);
951   Init *rhs = RHS->resolveReferences(R, RV);
952
953   if (LHS != lhs || RHS != rhs)
954     return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R,nullptr);
955   return Fold(&R, nullptr);
956 }
957
958 std::string BinOpInit::getAsString() const {
959   std::string Result;
960   switch (Opc) {
961   case CONCAT: Result = "!con"; break;
962   case ADD: Result = "!add"; break;
963   case AND: Result = "!and"; break;
964   case SHL: Result = "!shl"; break;
965   case SRA: Result = "!sra"; break;
966   case SRL: Result = "!srl"; break;
967   case EQ: Result = "!eq"; break;
968   case LISTCONCAT: Result = "!listconcat"; break;
969   case STRCONCAT: Result = "!strconcat"; break;
970   }
971   return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
972 }
973
974 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs,
975                                   Init *mhs, Init *rhs,
976                                   RecTy *Type) {
977   typedef std::pair<
978     std::pair<
979       std::pair<std::pair<unsigned, RecTy *>, Init *>,
980       Init *
981       >,
982     Init *
983     > Key;
984
985   static DenseMap<Key, std::unique_ptr<TernOpInit>> ThePool;
986
987   Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
988                                                                          Type),
989                                                           lhs),
990                                            mhs),
991                             rhs));
992
993   std::unique_ptr<TernOpInit> &I = ThePool[TheKey];
994   if (!I) I.reset(new TernOpInit(opc, lhs, mhs, rhs, Type));
995   return I.get();
996 }
997
998 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
999                            Record *CurRec, MultiClass *CurMultiClass);
1000
1001 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
1002                                RecTy *Type, Record *CurRec,
1003                                MultiClass *CurMultiClass) {
1004   // If this is a dag, recurse
1005   if (auto *TArg = dyn_cast<TypedInit>(Arg))
1006     if (TArg->getType()->getAsString() == "dag")
1007       return ForeachHelper(LHS, Arg, RHSo, Type, CurRec, CurMultiClass);
1008
1009   std::vector<Init *> NewOperands;
1010   for (int i = 0; i < RHSo->getNumOperands(); ++i) {
1011     if (auto *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i))) {
1012       if (Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1013                                            Type, CurRec, CurMultiClass))
1014         NewOperands.push_back(Result);
1015       else
1016         NewOperands.push_back(Arg);
1017     } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1018       NewOperands.push_back(Arg);
1019     } else {
1020       NewOperands.push_back(RHSo->getOperand(i));
1021     }
1022   }
1023
1024   // Now run the operator and use its result as the new leaf
1025   const OpInit *NewOp = RHSo->clone(NewOperands);
1026   Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
1027   return (NewVal != NewOp) ? NewVal : nullptr;
1028 }
1029
1030 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1031                            Record *CurRec, MultiClass *CurMultiClass) {
1032   DagInit *MHSd = dyn_cast<DagInit>(MHS);
1033   ListInit *MHSl = dyn_cast<ListInit>(MHS);
1034
1035   OpInit *RHSo = dyn_cast<OpInit>(RHS);
1036
1037   if (!RHSo) {
1038     PrintFatalError(CurRec->getLoc(), "!foreach requires an operator\n");
1039   }
1040
1041   TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1042
1043   if (!LHSt)
1044     PrintFatalError(CurRec->getLoc(), "!foreach requires typed variable\n");
1045
1046   if ((MHSd && isa<DagRecTy>(Type)) || (MHSl && isa<ListRecTy>(Type))) {
1047     if (MHSd) {
1048       Init *Val = MHSd->getOperator();
1049       Init *Result = EvaluateOperation(RHSo, LHS, Val,
1050                                        Type, CurRec, CurMultiClass);
1051       if (Result) {
1052         Val = Result;
1053       }
1054
1055       std::vector<std::pair<Init *, std::string> > args;
1056       for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1057         Init *Arg;
1058         std::string ArgName;
1059         Arg = MHSd->getArg(i);
1060         ArgName = MHSd->getArgName(i);
1061
1062         // Process args
1063         Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1064                                          CurRec, CurMultiClass);
1065         if (Result) {
1066           Arg = Result;
1067         }
1068
1069         // TODO: Process arg names
1070         args.push_back(std::make_pair(Arg, ArgName));
1071       }
1072
1073       return DagInit::get(Val, "", args);
1074     }
1075     if (MHSl) {
1076       std::vector<Init *> NewOperands;
1077       std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1078
1079       for (std::vector<Init *>::iterator li = NewList.begin(),
1080              liend = NewList.end();
1081            li != liend;
1082            ++li) {
1083         Init *Item = *li;
1084         NewOperands.clear();
1085         for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1086           // First, replace the foreach variable with the list item
1087           if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1088             NewOperands.push_back(Item);
1089           } else {
1090             NewOperands.push_back(RHSo->getOperand(i));
1091           }
1092         }
1093
1094         // Now run the operator and use its result as the new list item
1095         const OpInit *NewOp = RHSo->clone(NewOperands);
1096         Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1097         if (NewItem != NewOp)
1098           *li = NewItem;
1099       }
1100       return ListInit::get(NewList, MHSl->getType());
1101     }
1102   }
1103   return nullptr;
1104 }
1105
1106 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1107   switch (getOpcode()) {
1108   case SUBST: {
1109     DefInit *LHSd = dyn_cast<DefInit>(LHS);
1110     VarInit *LHSv = dyn_cast<VarInit>(LHS);
1111     StringInit *LHSs = dyn_cast<StringInit>(LHS);
1112
1113     DefInit *MHSd = dyn_cast<DefInit>(MHS);
1114     VarInit *MHSv = dyn_cast<VarInit>(MHS);
1115     StringInit *MHSs = dyn_cast<StringInit>(MHS);
1116
1117     DefInit *RHSd = dyn_cast<DefInit>(RHS);
1118     VarInit *RHSv = dyn_cast<VarInit>(RHS);
1119     StringInit *RHSs = dyn_cast<StringInit>(RHS);
1120
1121     if ((LHSd && MHSd && RHSd)
1122         || (LHSv && MHSv && RHSv)
1123         || (LHSs && MHSs && RHSs)) {
1124       if (RHSd) {
1125         Record *Val = RHSd->getDef();
1126         if (LHSd->getAsString() == RHSd->getAsString()) {
1127           Val = MHSd->getDef();
1128         }
1129         return DefInit::get(Val);
1130       }
1131       if (RHSv) {
1132         std::string Val = RHSv->getName();
1133         if (LHSv->getAsString() == RHSv->getAsString()) {
1134           Val = MHSv->getName();
1135         }
1136         return VarInit::get(Val, getType());
1137       }
1138       if (RHSs) {
1139         std::string Val = RHSs->getValue();
1140
1141         std::string::size_type found;
1142         std::string::size_type idx = 0;
1143         do {
1144           found = Val.find(LHSs->getValue(), idx);
1145           if (found != std::string::npos) {
1146             Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1147           }
1148           idx = found +  MHSs->getValue().size();
1149         } while (found != std::string::npos);
1150
1151         return StringInit::get(Val);
1152       }
1153     }
1154     break;
1155   }
1156
1157   case FOREACH: {
1158     Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1159                                  CurRec, CurMultiClass);
1160     if (Result) {
1161       return Result;
1162     }
1163     break;
1164   }
1165
1166   case IF: {
1167     IntInit *LHSi = dyn_cast<IntInit>(LHS);
1168     if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1169       LHSi = dyn_cast<IntInit>(I);
1170     if (LHSi) {
1171       if (LHSi->getValue()) {
1172         return MHS;
1173       } else {
1174         return RHS;
1175       }
1176     }
1177     break;
1178   }
1179   }
1180
1181   return const_cast<TernOpInit *>(this);
1182 }
1183
1184 Init *TernOpInit::resolveReferences(Record &R,
1185                                     const RecordVal *RV) const {
1186   Init *lhs = LHS->resolveReferences(R, RV);
1187
1188   if (Opc == IF && lhs != LHS) {
1189     IntInit *Value = dyn_cast<IntInit>(lhs);
1190     if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1191       Value = dyn_cast<IntInit>(I);
1192     if (Value) {
1193       // Short-circuit
1194       if (Value->getValue()) {
1195         Init *mhs = MHS->resolveReferences(R, RV);
1196         return (TernOpInit::get(getOpcode(), lhs, mhs,
1197                                 RHS, getType()))->Fold(&R, nullptr);
1198       } else {
1199         Init *rhs = RHS->resolveReferences(R, RV);
1200         return (TernOpInit::get(getOpcode(), lhs, MHS,
1201                                 rhs, getType()))->Fold(&R, nullptr);
1202       }
1203     }
1204   }
1205
1206   Init *mhs = MHS->resolveReferences(R, RV);
1207   Init *rhs = RHS->resolveReferences(R, RV);
1208
1209   if (LHS != lhs || MHS != mhs || RHS != rhs)
1210     return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1211                             getType()))->Fold(&R, nullptr);
1212   return Fold(&R, nullptr);
1213 }
1214
1215 std::string TernOpInit::getAsString() const {
1216   std::string Result;
1217   switch (Opc) {
1218   case SUBST: Result = "!subst"; break;
1219   case FOREACH: Result = "!foreach"; break;
1220   case IF: Result = "!if"; break;
1221  }
1222   return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
1223     + RHS->getAsString() + ")";
1224 }
1225
1226 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1227   if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
1228     if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
1229       return Field->getType();
1230   return nullptr;
1231 }
1232
1233 Init *
1234 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1235   BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1236   if (!T) return nullptr;  // Cannot subscript a non-bits variable.
1237   unsigned NumBits = T->getNumBits();
1238
1239   SmallVector<Init *, 16> NewBits(Bits.size());
1240   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1241     if (Bits[i] >= NumBits)
1242       return nullptr;
1243
1244     NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1245   }
1246   return BitsInit::get(NewBits);
1247 }
1248
1249 Init *
1250 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1251   ListRecTy *T = dyn_cast<ListRecTy>(getType());
1252   if (!T) return nullptr;  // Cannot subscript a non-list variable.
1253
1254   if (Elements.size() == 1)
1255     return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1256
1257   std::vector<Init*> ListInits;
1258   ListInits.reserve(Elements.size());
1259   for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1260     ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1261                                                 Elements[i]));
1262   return ListInit::get(ListInits, T);
1263 }
1264
1265
1266 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1267   Init *Value = StringInit::get(VN);
1268   return VarInit::get(Value, T);
1269 }
1270
1271 VarInit *VarInit::get(Init *VN, RecTy *T) {
1272   typedef std::pair<RecTy *, Init *> Key;
1273   static DenseMap<Key, std::unique_ptr<VarInit>> ThePool;
1274
1275   Key TheKey(std::make_pair(T, VN));
1276
1277   std::unique_ptr<VarInit> &I = ThePool[TheKey];
1278   if (!I) I.reset(new VarInit(VN, T));
1279   return I.get();
1280 }
1281
1282 const std::string &VarInit::getName() const {
1283   StringInit *NameString = cast<StringInit>(getNameInit());
1284   return NameString->getValue();
1285 }
1286
1287 Init *VarInit::getBit(unsigned Bit) const {
1288   if (getType() == BitRecTy::get())
1289     return const_cast<VarInit*>(this);
1290   return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1291 }
1292
1293 Init *VarInit::resolveListElementReference(Record &R,
1294                                            const RecordVal *IRV,
1295                                            unsigned Elt) const {
1296   if (R.isTemplateArg(getNameInit())) return nullptr;
1297   if (IRV && IRV->getNameInit() != getNameInit()) return nullptr;
1298
1299   RecordVal *RV = R.getValue(getNameInit());
1300   assert(RV && "Reference to a non-existent variable?");
1301   ListInit *LI = dyn_cast<ListInit>(RV->getValue());
1302   if (!LI) {
1303     TypedInit *VI = cast<TypedInit>(RV->getValue());
1304     return VarListElementInit::get(VI, Elt);
1305   }
1306
1307   if (Elt >= LI->getSize())
1308     return nullptr;  // Out of range reference.
1309   Init *E = LI->getElement(Elt);
1310   // If the element is set to some value, or if we are resolving a reference
1311   // to a specific variable and that variable is explicitly unset, then
1312   // replace the VarListElementInit with it.
1313   if (IRV || !isa<UnsetInit>(E))
1314     return E;
1315   return nullptr;
1316 }
1317
1318
1319 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1320   if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
1321     if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1322       return RV->getType();
1323   return nullptr;
1324 }
1325
1326 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1327                             const std::string &FieldName) const {
1328   if (isa<RecordRecTy>(getType()))
1329     if (const RecordVal *Val = R.getValue(VarName)) {
1330       if (RV != Val && (RV || isa<UnsetInit>(Val->getValue())))
1331         return nullptr;
1332       Init *TheInit = Val->getValue();
1333       assert(TheInit != this && "Infinite loop detected!");
1334       if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1335         return I;
1336       else
1337         return nullptr;
1338     }
1339   return nullptr;
1340 }
1341
1342 /// resolveReferences - This method is used by classes that refer to other
1343 /// variables which may not be defined at the time the expression is formed.
1344 /// If a value is set for the variable later, this method will be called on
1345 /// users of the value to allow the value to propagate out.
1346 ///
1347 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1348   if (RecordVal *Val = R.getValue(VarName))
1349     if (RV == Val || (!RV && !isa<UnsetInit>(Val->getValue())))
1350       return Val->getValue();
1351   return const_cast<VarInit *>(this);
1352 }
1353
1354 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1355   typedef std::pair<TypedInit *, unsigned> Key;
1356   static DenseMap<Key, std::unique_ptr<VarBitInit>> ThePool;
1357
1358   Key TheKey(std::make_pair(T, B));
1359
1360   std::unique_ptr<VarBitInit> &I = ThePool[TheKey];
1361   if (!I) I.reset(new VarBitInit(T, B));
1362   return I.get();
1363 }
1364
1365 std::string VarBitInit::getAsString() const {
1366    return TI->getAsString() + "{" + utostr(Bit) + "}";
1367 }
1368
1369 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1370   Init *I = TI->resolveReferences(R, RV);
1371   if (TI != I)
1372     return I->getBit(getBitNum());
1373
1374   return const_cast<VarBitInit*>(this);
1375 }
1376
1377 VarListElementInit *VarListElementInit::get(TypedInit *T,
1378                                             unsigned E) {
1379   typedef std::pair<TypedInit *, unsigned> Key;
1380   static DenseMap<Key, std::unique_ptr<VarListElementInit>> ThePool;
1381
1382   Key TheKey(std::make_pair(T, E));
1383
1384   std::unique_ptr<VarListElementInit> &I = ThePool[TheKey];
1385   if (!I) I.reset(new VarListElementInit(T, E));
1386   return I.get();
1387 }
1388
1389 std::string VarListElementInit::getAsString() const {
1390   return TI->getAsString() + "[" + utostr(Element) + "]";
1391 }
1392
1393 Init *
1394 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1395   if (Init *I = getVariable()->resolveListElementReference(R, RV,
1396                                                            getElementNum()))
1397     return I;
1398   return const_cast<VarListElementInit *>(this);
1399 }
1400
1401 Init *VarListElementInit::getBit(unsigned Bit) const {
1402   if (getType() == BitRecTy::get())
1403     return const_cast<VarListElementInit*>(this);
1404   return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1405 }
1406
1407 Init *VarListElementInit:: resolveListElementReference(Record &R,
1408                                                        const RecordVal *RV,
1409                                                        unsigned Elt) const {
1410   Init *Result = TI->resolveListElementReference(R, RV, Element);
1411   
1412   if (Result) {
1413     if (TypedInit *TInit = dyn_cast<TypedInit>(Result)) {
1414       Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1415       if (Result2) return Result2;
1416       return VarListElementInit::get(TInit, Elt);
1417     }
1418     return Result;
1419   }
1420  
1421   return nullptr;
1422 }
1423
1424 DefInit *DefInit::get(Record *R) {
1425   return R->getDefInit();
1426 }
1427
1428 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1429   if (const RecordVal *RV = Def->getValue(FieldName))
1430     return RV->getType();
1431   return nullptr;
1432 }
1433
1434 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1435                             const std::string &FieldName) const {
1436   return Def->getValue(FieldName)->getValue();
1437 }
1438
1439
1440 std::string DefInit::getAsString() const {
1441   return Def->getName();
1442 }
1443
1444 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1445   typedef std::pair<Init *, TableGenStringKey> Key;
1446   static DenseMap<Key, std::unique_ptr<FieldInit>> ThePool;
1447
1448   Key TheKey(std::make_pair(R, FN));
1449
1450   std::unique_ptr<FieldInit> &I = ThePool[TheKey];
1451   if (!I) I.reset(new FieldInit(R, FN));
1452   return I.get();
1453 }
1454
1455 Init *FieldInit::getBit(unsigned Bit) const {
1456   if (getType() == BitRecTy::get())
1457     return const_cast<FieldInit*>(this);
1458   return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1459 }
1460
1461 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1462                                              unsigned Elt) const {
1463   if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1464     if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
1465       if (Elt >= LI->getSize()) return nullptr;
1466       Init *E = LI->getElement(Elt);
1467
1468       // If the element is set to some value, or if we are resolving a
1469       // reference to a specific variable and that variable is explicitly
1470       // unset, then replace the VarListElementInit with it.
1471       if (RV || !isa<UnsetInit>(E))
1472         return E;
1473     }
1474   return nullptr;
1475 }
1476
1477 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1478   Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1479
1480   Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1481   if (BitsVal) {
1482     Init *BVR = BitsVal->resolveReferences(R, RV);
1483     return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1484   }
1485
1486   if (NewRec != Rec) {
1487     return FieldInit::get(NewRec, FieldName);
1488   }
1489   return const_cast<FieldInit *>(this);
1490 }
1491
1492 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, const std::string &VN,
1493                            ArrayRef<Init *> ArgRange,
1494                            ArrayRef<std::string> NameRange) {
1495   ID.AddPointer(V);
1496   ID.AddString(VN);
1497
1498   ArrayRef<Init *>::iterator Arg  = ArgRange.begin();
1499   ArrayRef<std::string>::iterator  Name = NameRange.begin();
1500   while (Arg != ArgRange.end()) {
1501     assert(Name != NameRange.end() && "Arg name underflow!");
1502     ID.AddPointer(*Arg++);
1503     ID.AddString(*Name++);
1504   }
1505   assert(Name == NameRange.end() && "Arg name overflow!");
1506 }
1507
1508 DagInit *
1509 DagInit::get(Init *V, const std::string &VN,
1510              ArrayRef<Init *> ArgRange,
1511              ArrayRef<std::string> NameRange) {
1512   static FoldingSet<DagInit> ThePool;
1513   static std::vector<std::unique_ptr<DagInit>> TheActualPool;
1514
1515   FoldingSetNodeID ID;
1516   ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1517
1518   void *IP = nullptr;
1519   if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1520     return I;
1521
1522   DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1523   ThePool.InsertNode(I, IP);
1524   TheActualPool.push_back(std::unique_ptr<DagInit>(I));
1525   return I;
1526 }
1527
1528 DagInit *
1529 DagInit::get(Init *V, const std::string &VN,
1530              const std::vector<std::pair<Init*, std::string> > &args) {
1531   std::vector<Init *> Args;
1532   std::vector<std::string> Names;
1533
1534   for (const auto &Arg : args) {
1535     Args.push_back(Arg.first);
1536     Names.push_back(Arg.second);
1537   }
1538
1539   return DagInit::get(V, VN, Args, Names);
1540 }
1541
1542 void DagInit::Profile(FoldingSetNodeID &ID) const {
1543   ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1544 }
1545
1546 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1547   std::vector<Init*> NewArgs;
1548   for (unsigned i = 0, e = Args.size(); i != e; ++i)
1549     NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1550
1551   Init *Op = Val->resolveReferences(R, RV);
1552
1553   if (Args != NewArgs || Op != Val)
1554     return DagInit::get(Op, ValName, NewArgs, ArgNames);
1555
1556   return const_cast<DagInit *>(this);
1557 }
1558
1559
1560 std::string DagInit::getAsString() const {
1561   std::string Result = "(" + Val->getAsString();
1562   if (!ValName.empty())
1563     Result += ":" + ValName;
1564   if (!Args.empty()) {
1565     Result += " " + Args[0]->getAsString();
1566     if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1567     for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1568       Result += ", " + Args[i]->getAsString();
1569       if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1570     }
1571   }
1572   return Result + ")";
1573 }
1574
1575
1576 //===----------------------------------------------------------------------===//
1577 //    Other implementations
1578 //===----------------------------------------------------------------------===//
1579
1580 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1581   : Name(N), Ty(T), Prefix(P) {
1582   Value = Ty->convertValue(UnsetInit::get());
1583   assert(Value && "Cannot create unset value for current type!");
1584 }
1585
1586 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1587   : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1588   Value = Ty->convertValue(UnsetInit::get());
1589   assert(Value && "Cannot create unset value for current type!");
1590 }
1591
1592 const std::string &RecordVal::getName() const {
1593   return cast<StringInit>(Name)->getValue();
1594 }
1595
1596 void RecordVal::dump() const { errs() << *this; }
1597
1598 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1599   if (getPrefix()) OS << "field ";
1600   OS << *getType() << " " << getNameInitAsString();
1601
1602   if (getValue())
1603     OS << " = " << *getValue();
1604
1605   if (PrintSem) OS << ";\n";
1606 }
1607
1608 unsigned Record::LastID = 0;
1609
1610 void Record::init() {
1611   checkName();
1612
1613   // Every record potentially has a def at the top.  This value is
1614   // replaced with the top-level def name at instantiation time.
1615   RecordVal DN("NAME", StringRecTy::get(), 0);
1616   addValue(DN);
1617 }
1618
1619 void Record::checkName() {
1620   // Ensure the record name has string type.
1621   const TypedInit *TypedName = cast<const TypedInit>(Name);
1622   RecTy *Type = TypedName->getType();
1623   if (!isa<StringRecTy>(Type))
1624     PrintFatalError(getLoc(), "Record name is not a string!");
1625 }
1626
1627 DefInit *Record::getDefInit() {
1628   static DenseMap<Record *, std::unique_ptr<DefInit>> ThePool;
1629   if (TheInit)
1630     return TheInit;
1631
1632   std::unique_ptr<DefInit> &I = ThePool[this];
1633   if (!I) I.reset(new DefInit(this, new RecordRecTy(this)));
1634   return I.get();
1635 }
1636
1637 const std::string &Record::getName() const {
1638   return cast<StringInit>(Name)->getValue();
1639 }
1640
1641 void Record::setName(Init *NewName) {
1642   Name = NewName;
1643   checkName();
1644   // DO NOT resolve record values to the name at this point because
1645   // there might be default values for arguments of this def.  Those
1646   // arguments might not have been resolved yet so we don't want to
1647   // prematurely assume values for those arguments were not passed to
1648   // this def.
1649   //
1650   // Nonetheless, it may be that some of this Record's values
1651   // reference the record name.  Indeed, the reason for having the
1652   // record name be an Init is to provide this flexibility.  The extra
1653   // resolve steps after completely instantiating defs takes care of
1654   // this.  See TGParser::ParseDef and TGParser::ParseDefm.
1655 }
1656
1657 void Record::setName(const std::string &Name) {
1658   setName(StringInit::get(Name));
1659 }
1660
1661 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1662 /// reference to RV with the RHS of RV.  If RV is null, we resolve all possible
1663 /// references.
1664 void Record::resolveReferencesTo(const RecordVal *RV) {
1665   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1666     if (RV == &Values[i]) // Skip resolve the same field as the given one
1667       continue;
1668     if (Init *V = Values[i].getValue())
1669       if (Values[i].setValue(V->resolveReferences(*this, RV)))
1670         PrintFatalError(getLoc(), "Invalid value is found when setting '"
1671                       + Values[i].getNameInitAsString()
1672                       + "' after resolving references"
1673                       + (RV ? " against '" + RV->getNameInitAsString()
1674                               + "' of ("
1675                               + RV->getValue()->getAsUnquotedString() + ")"
1676                             : "")
1677                       + "\n");
1678   }
1679   Init *OldName = getNameInit();
1680   Init *NewName = Name->resolveReferences(*this, RV);
1681   if (NewName != OldName) {
1682     // Re-register with RecordKeeper.
1683     setName(NewName);
1684   }
1685 }
1686
1687 void Record::dump() const { errs() << *this; }
1688
1689 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1690   OS << R.getNameInitAsString();
1691
1692   const std::vector<Init *> &TArgs = R.getTemplateArgs();
1693   if (!TArgs.empty()) {
1694     OS << "<";
1695     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1696       if (i) OS << ", ";
1697       const RecordVal *RV = R.getValue(TArgs[i]);
1698       assert(RV && "Template argument record not found??");
1699       RV->print(OS, false);
1700     }
1701     OS << ">";
1702   }
1703
1704   OS << " {";
1705   const std::vector<Record*> &SC = R.getSuperClasses();
1706   if (!SC.empty()) {
1707     OS << "\t//";
1708     for (unsigned i = 0, e = SC.size(); i != e; ++i)
1709       OS << " " << SC[i]->getNameInitAsString();
1710   }
1711   OS << "\n";
1712
1713   const std::vector<RecordVal> &Vals = R.getValues();
1714   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1715     if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1716       OS << Vals[i];
1717   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1718     if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1719       OS << Vals[i];
1720
1721   return OS << "}\n";
1722 }
1723
1724 /// getValueInit - Return the initializer for a value with the specified name,
1725 /// or abort if the field does not exist.
1726 ///
1727 Init *Record::getValueInit(StringRef FieldName) const {
1728   const RecordVal *R = getValue(FieldName);
1729   if (!R || !R->getValue())
1730     PrintFatalError(getLoc(), "Record `" + getName() +
1731       "' does not have a field named `" + FieldName + "'!\n");
1732   return R->getValue();
1733 }
1734
1735
1736 /// getValueAsString - This method looks up the specified field and returns its
1737 /// value as a string, aborts if the field does not exist or if
1738 /// the value is not a string.
1739 ///
1740 std::string Record::getValueAsString(StringRef FieldName) const {
1741   const RecordVal *R = getValue(FieldName);
1742   if (!R || !R->getValue())
1743     PrintFatalError(getLoc(), "Record `" + getName() +
1744       "' does not have a field named `" + FieldName + "'!\n");
1745
1746   if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1747     return SI->getValue();
1748   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1749     FieldName + "' does not have a string initializer!");
1750 }
1751
1752 /// getValueAsBitsInit - This method looks up the specified field and returns
1753 /// its value as a BitsInit, aborts if the field does not exist or if
1754 /// the value is not the right type.
1755 ///
1756 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1757   const RecordVal *R = getValue(FieldName);
1758   if (!R || !R->getValue())
1759     PrintFatalError(getLoc(), "Record `" + getName() +
1760       "' does not have a field named `" + FieldName + "'!\n");
1761
1762   if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
1763     return BI;
1764   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1765     FieldName + "' does not have a BitsInit initializer!");
1766 }
1767
1768 /// getValueAsListInit - This method looks up the specified field and returns
1769 /// its value as a ListInit, aborting if the field does not exist or if
1770 /// the value is not the right type.
1771 ///
1772 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1773   const RecordVal *R = getValue(FieldName);
1774   if (!R || !R->getValue())
1775     PrintFatalError(getLoc(), "Record `" + getName() +
1776       "' does not have a field named `" + FieldName + "'!\n");
1777
1778   if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
1779     return LI;
1780   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1781     FieldName + "' does not have a list initializer!");
1782 }
1783
1784 /// getValueAsListOfDefs - This method looks up the specified field and returns
1785 /// its value as a vector of records, aborting if the field does not exist
1786 /// or if the value is not the right type.
1787 ///
1788 std::vector<Record*>
1789 Record::getValueAsListOfDefs(StringRef FieldName) const {
1790   ListInit *List = getValueAsListInit(FieldName);
1791   std::vector<Record*> Defs;
1792   for (unsigned i = 0; i < List->getSize(); i++) {
1793     if (DefInit *DI = dyn_cast<DefInit>(List->getElement(i))) {
1794       Defs.push_back(DI->getDef());
1795     } else {
1796       PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1797         FieldName + "' list is not entirely DefInit!");
1798     }
1799   }
1800   return Defs;
1801 }
1802
1803 /// getValueAsInt - This method looks up the specified field and returns its
1804 /// value as an int64_t, aborting if the field does not exist or if the value
1805 /// is not the right type.
1806 ///
1807 int64_t Record::getValueAsInt(StringRef FieldName) const {
1808   const RecordVal *R = getValue(FieldName);
1809   if (!R || !R->getValue())
1810     PrintFatalError(getLoc(), "Record `" + getName() +
1811       "' does not have a field named `" + FieldName + "'!\n");
1812
1813   if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
1814     return II->getValue();
1815   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1816     FieldName + "' does not have an int initializer!");
1817 }
1818
1819 /// getValueAsListOfInts - This method looks up the specified field and returns
1820 /// its value as a vector of integers, aborting if the field does not exist or
1821 /// if the value is not the right type.
1822 ///
1823 std::vector<int64_t>
1824 Record::getValueAsListOfInts(StringRef FieldName) const {
1825   ListInit *List = getValueAsListInit(FieldName);
1826   std::vector<int64_t> Ints;
1827   for (unsigned i = 0; i < List->getSize(); i++) {
1828     if (IntInit *II = dyn_cast<IntInit>(List->getElement(i))) {
1829       Ints.push_back(II->getValue());
1830     } else {
1831       PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1832         FieldName + "' does not have a list of ints initializer!");
1833     }
1834   }
1835   return Ints;
1836 }
1837
1838 /// getValueAsListOfStrings - This method looks up the specified field and
1839 /// returns its value as a vector of strings, aborting if the field does not
1840 /// exist or if the value is not the right type.
1841 ///
1842 std::vector<std::string>
1843 Record::getValueAsListOfStrings(StringRef FieldName) const {
1844   ListInit *List = getValueAsListInit(FieldName);
1845   std::vector<std::string> Strings;
1846   for (unsigned i = 0; i < List->getSize(); i++) {
1847     if (StringInit *II = dyn_cast<StringInit>(List->getElement(i))) {
1848       Strings.push_back(II->getValue());
1849     } else {
1850       PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1851         FieldName + "' does not have a list of strings initializer!");
1852     }
1853   }
1854   return Strings;
1855 }
1856
1857 /// getValueAsDef - This method looks up the specified field and returns its
1858 /// value as a Record, aborting if the field does not exist or if the value
1859 /// is not the right type.
1860 ///
1861 Record *Record::getValueAsDef(StringRef FieldName) const {
1862   const RecordVal *R = getValue(FieldName);
1863   if (!R || !R->getValue())
1864     PrintFatalError(getLoc(), "Record `" + getName() +
1865       "' does not have a field named `" + FieldName + "'!\n");
1866
1867   if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
1868     return DI->getDef();
1869   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1870     FieldName + "' does not have a def initializer!");
1871 }
1872
1873 /// getValueAsBit - This method looks up the specified field and returns its
1874 /// value as a bit, aborting if the field does not exist or if the value is
1875 /// not the right type.
1876 ///
1877 bool Record::getValueAsBit(StringRef FieldName) const {
1878   const RecordVal *R = getValue(FieldName);
1879   if (!R || !R->getValue())
1880     PrintFatalError(getLoc(), "Record `" + getName() +
1881       "' does not have a field named `" + FieldName + "'!\n");
1882
1883   if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1884     return BI->getValue();
1885   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1886     FieldName + "' does not have a bit initializer!");
1887 }
1888
1889 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1890   const RecordVal *R = getValue(FieldName);
1891   if (!R || !R->getValue())
1892     PrintFatalError(getLoc(), "Record `" + getName() +
1893       "' does not have a field named `" + FieldName.str() + "'!\n");
1894
1895   if (isa<UnsetInit>(R->getValue())) {
1896     Unset = true;
1897     return false;
1898   }
1899   Unset = false;
1900   if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1901     return BI->getValue();
1902   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1903     FieldName + "' does not have a bit initializer!");
1904 }
1905
1906 /// getValueAsDag - This method looks up the specified field and returns its
1907 /// value as an Dag, aborting if the field does not exist or if the value is
1908 /// not the right type.
1909 ///
1910 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1911   const RecordVal *R = getValue(FieldName);
1912   if (!R || !R->getValue())
1913     PrintFatalError(getLoc(), "Record `" + getName() +
1914       "' does not have a field named `" + FieldName + "'!\n");
1915
1916   if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
1917     return DI;
1918   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1919     FieldName + "' does not have a dag initializer!");
1920 }
1921
1922
1923 void MultiClass::dump() const {
1924   errs() << "Record:\n";
1925   Rec.dump();
1926
1927   errs() << "Defs:\n";
1928   for (const auto &Proto : DefPrototypes) {
1929     Proto->dump();
1930   }
1931 }
1932
1933
1934 void RecordKeeper::dump() const { errs() << *this; }
1935
1936 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1937   OS << "------------- Classes -----------------\n";
1938   const auto &Classes = RK.getClasses();
1939   for (const auto &C : Classes)
1940     OS << "class " << *C.second;
1941
1942   OS << "------------- Defs -----------------\n";
1943   const auto &Defs = RK.getDefs();
1944   for (const auto &D : Defs)
1945     OS << "def " << *D.second;
1946   return OS;
1947 }
1948
1949
1950 /// getAllDerivedDefinitions - This method returns all concrete definitions
1951 /// that derive from the specified class name.  If a class with the specified
1952 /// name does not exist, an error is printed and true is returned.
1953 std::vector<Record*>
1954 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
1955   Record *Class = getClass(ClassName);
1956   if (!Class)
1957     PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
1958
1959   std::vector<Record*> Defs;
1960   for (const auto &D : getDefs())
1961     if (D.second->isSubClassOf(Class))
1962       Defs.push_back(D.second.get());
1963
1964   return Defs;
1965 }
1966
1967 /// QualifyName - Return an Init with a qualifier prefix referring
1968 /// to CurRec's name.
1969 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1970                         Init *Name, const std::string &Scoper) {
1971   RecTy *Type = cast<TypedInit>(Name)->getType();
1972
1973   BinOpInit *NewName =
1974     BinOpInit::get(BinOpInit::STRCONCAT, 
1975                       BinOpInit::get(BinOpInit::STRCONCAT,
1976                                         CurRec.getNameInit(),
1977                                         StringInit::get(Scoper),
1978                                         Type)->Fold(&CurRec, CurMultiClass),
1979                       Name,
1980                       Type);
1981
1982   if (CurMultiClass && Scoper != "::") {
1983     NewName =
1984       BinOpInit::get(BinOpInit::STRCONCAT, 
1985                         BinOpInit::get(BinOpInit::STRCONCAT,
1986                                           CurMultiClass->Rec.getNameInit(),
1987                                           StringInit::get("::"),
1988                                           Type)->Fold(&CurRec, CurMultiClass),
1989                         NewName->Fold(&CurRec, CurMultiClass),
1990                         Type);
1991   }
1992
1993   return NewName->Fold(&CurRec, CurMultiClass);
1994 }
1995
1996 /// QualifyName - Return an Init with a qualifier prefix referring
1997 /// to CurRec's name.
1998 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1999                         const std::string &Name,
2000                         const std::string &Scoper) {
2001   return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);
2002 }