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