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