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