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