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