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