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