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