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