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