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