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