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