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