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