1 //===- Record.cpp - Record implementation ---------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implement the tablegen record classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/TableGen/Record.h"
15 #include "llvm/TableGen/Error.h"
16 #include "llvm/Support/DataTypes.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/Format.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
28 //===----------------------------------------------------------------------===//
29 // std::string wrapper for DenseMap purposes
30 //===----------------------------------------------------------------------===//
32 /// TableGenStringKey - This is a wrapper for std::string suitable for
33 /// using as a key to a DenseMap. Because there isn't a particularly
34 /// good way to indicate tombstone or empty keys for strings, we want
35 /// to wrap std::string to indicate that this is a "special" string
36 /// not expected to take on certain values (those of the tombstone and
37 /// empty keys). This makes things a little safer as it clarifies
38 /// that DenseMap is really not appropriate for general strings.
40 class TableGenStringKey {
42 TableGenStringKey(const std::string &str) : data(str) {}
43 TableGenStringKey(const char *str) : data(str) {}
45 const std::string &str() const { return data; }
51 /// Specialize DenseMapInfo for TableGenStringKey.
54 template<> struct DenseMapInfo<TableGenStringKey> {
55 static inline TableGenStringKey getEmptyKey() {
56 TableGenStringKey Empty("<<<EMPTY KEY>>>");
59 static inline TableGenStringKey getTombstoneKey() {
60 TableGenStringKey Tombstone("<<<TOMBSTONE KEY>>>");
63 static unsigned getHashValue(const TableGenStringKey& Val) {
64 return HashString(Val.str());
66 static bool isEqual(const TableGenStringKey& LHS,
67 const TableGenStringKey& RHS) {
68 return LHS.str() == RHS.str();
74 //===----------------------------------------------------------------------===//
75 // Type implementations
76 //===----------------------------------------------------------------------===//
78 BitRecTy BitRecTy::Shared;
79 IntRecTy IntRecTy::Shared;
80 StringRecTy StringRecTy::Shared;
81 CodeRecTy CodeRecTy::Shared;
82 DagRecTy DagRecTy::Shared;
84 void RecTy::dump() const { print(errs()); }
86 ListRecTy *RecTy::getListTy() {
88 ListTy = new ListRecTy(this);
92 Init *BitRecTy::convertValue(BitsInit *BI) {
93 if (BI->getNumBits() != 1) return 0; // Only accept if just one bit!
97 bool BitRecTy::baseClassOf(const BitsRecTy *RHS) const {
98 return RHS->getNumBits() == 1;
101 Init *BitRecTy::convertValue(IntInit *II) {
102 int64_t Val = II->getValue();
103 if (Val != 0 && Val != 1) return 0; // Only accept 0 or 1 for a bit!
105 return BitInit::get(Val != 0);
108 Init *BitRecTy::convertValue(TypedInit *VI) {
109 if (dynamic_cast<BitRecTy*>(VI->getType()))
110 return VI; // Accept variable if it is already of bit type!
114 BitsRecTy *BitsRecTy::get(unsigned Sz) {
115 static std::vector<BitsRecTy*> Shared;
116 if (Sz >= Shared.size())
117 Shared.resize(Sz + 1);
118 BitsRecTy *&Ty = Shared[Sz];
120 Ty = new BitsRecTy(Sz);
124 std::string BitsRecTy::getAsString() const {
125 return "bits<" + utostr(Size) + ">";
128 Init *BitsRecTy::convertValue(UnsetInit *UI) {
129 SmallVector<Init *, 16> NewBits(Size);
131 for (unsigned i = 0; i != Size; ++i)
132 NewBits[i] = UnsetInit::get();
134 return BitsInit::get(NewBits);
137 Init *BitsRecTy::convertValue(BitInit *UI) {
138 if (Size != 1) return 0; // Can only convert single bit.
139 return BitsInit::get(UI);
142 /// canFitInBitfield - Return true if the number of bits is large enough to hold
143 /// the integer value.
144 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
145 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
146 return (NumBits >= sizeof(Value) * 8) ||
147 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
150 /// convertValue from Int initializer to bits type: Split the integer up into the
151 /// appropriate bits.
153 Init *BitsRecTy::convertValue(IntInit *II) {
154 int64_t Value = II->getValue();
155 // Make sure this bitfield is large enough to hold the integer value.
156 if (!canFitInBitfield(Value, Size))
159 SmallVector<Init *, 16> NewBits(Size);
161 for (unsigned i = 0; i != Size; ++i)
162 NewBits[i] = BitInit::get(Value & (1LL << i));
164 return BitsInit::get(NewBits);
167 Init *BitsRecTy::convertValue(BitsInit *BI) {
168 // If the number of bits is right, return it. Otherwise we need to expand or
170 if (BI->getNumBits() == Size) return BI;
174 Init *BitsRecTy::convertValue(TypedInit *VI) {
175 if (BitsRecTy *BRT = dynamic_cast<BitsRecTy*>(VI->getType()))
176 if (BRT->Size == Size) {
177 SmallVector<Init *, 16> NewBits(Size);
179 for (unsigned i = 0; i != Size; ++i)
180 NewBits[i] = VarBitInit::get(VI, i);
181 return BitsInit::get(NewBits);
184 if (Size == 1 && dynamic_cast<BitRecTy*>(VI->getType()))
185 return BitsInit::get(VI);
187 if (TernOpInit *Tern = dynamic_cast<TernOpInit*>(VI)) {
188 if (Tern->getOpcode() == TernOpInit::IF) {
189 Init *LHS = Tern->getLHS();
190 Init *MHS = Tern->getMHS();
191 Init *RHS = Tern->getRHS();
193 IntInit *MHSi = dynamic_cast<IntInit*>(MHS);
194 IntInit *RHSi = dynamic_cast<IntInit*>(RHS);
197 int64_t MHSVal = MHSi->getValue();
198 int64_t RHSVal = RHSi->getValue();
200 if (canFitInBitfield(MHSVal, Size) && canFitInBitfield(RHSVal, Size)) {
201 SmallVector<Init *, 16> NewBits(Size);
203 for (unsigned i = 0; i != Size; ++i)
205 TernOpInit::get(TernOpInit::IF, LHS,
206 IntInit::get((MHSVal & (1LL << i)) ? 1 : 0),
207 IntInit::get((RHSVal & (1LL << i)) ? 1 : 0),
210 return BitsInit::get(NewBits);
213 BitsInit *MHSbs = dynamic_cast<BitsInit*>(MHS);
214 BitsInit *RHSbs = dynamic_cast<BitsInit*>(RHS);
216 if (MHSbs && RHSbs) {
217 SmallVector<Init *, 16> NewBits(Size);
219 for (unsigned i = 0; i != Size; ++i)
220 NewBits[i] = TernOpInit::get(TernOpInit::IF, LHS,
225 return BitsInit::get(NewBits);
234 Init *IntRecTy::convertValue(BitInit *BI) {
235 return IntInit::get(BI->getValue());
238 Init *IntRecTy::convertValue(BitsInit *BI) {
240 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
241 if (BitInit *Bit = dynamic_cast<BitInit*>(BI->getBit(i))) {
242 Result |= Bit->getValue() << i;
246 return IntInit::get(Result);
249 Init *IntRecTy::convertValue(TypedInit *TI) {
250 if (TI->getType()->typeIsConvertibleTo(this))
251 return TI; // Accept variable if already of the right type!
255 Init *StringRecTy::convertValue(UnOpInit *BO) {
256 if (BO->getOpcode() == UnOpInit::CAST) {
257 Init *L = BO->getOperand()->convertInitializerTo(this);
258 if (L == 0) return 0;
259 if (L != BO->getOperand())
260 return UnOpInit::get(UnOpInit::CAST, L, new StringRecTy);
264 return convertValue((TypedInit*)BO);
267 Init *StringRecTy::convertValue(BinOpInit *BO) {
268 if (BO->getOpcode() == BinOpInit::STRCONCAT) {
269 Init *L = BO->getLHS()->convertInitializerTo(this);
270 Init *R = BO->getRHS()->convertInitializerTo(this);
271 if (L == 0 || R == 0) return 0;
272 if (L != BO->getLHS() || R != BO->getRHS())
273 return BinOpInit::get(BinOpInit::STRCONCAT, L, R, new StringRecTy);
277 return convertValue((TypedInit*)BO);
281 Init *StringRecTy::convertValue(TypedInit *TI) {
282 if (dynamic_cast<StringRecTy*>(TI->getType()))
283 return TI; // Accept variable if already of the right type!
287 std::string ListRecTy::getAsString() const {
288 return "list<" + Ty->getAsString() + ">";
291 Init *ListRecTy::convertValue(ListInit *LI) {
292 std::vector<Init*> Elements;
294 // Verify that all of the elements of the list are subclasses of the
295 // appropriate class!
296 for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
297 if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
298 Elements.push_back(CI);
302 ListRecTy *LType = dynamic_cast<ListRecTy*>(LI->getType());
307 return ListInit::get(Elements, this);
310 Init *ListRecTy::convertValue(TypedInit *TI) {
311 // Ensure that TI is compatible with our class.
312 if (ListRecTy *LRT = dynamic_cast<ListRecTy*>(TI->getType()))
313 if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
318 Init *CodeRecTy::convertValue(TypedInit *TI) {
319 if (TI->getType()->typeIsConvertibleTo(this))
324 Init *DagRecTy::convertValue(TypedInit *TI) {
325 if (TI->getType()->typeIsConvertibleTo(this))
330 Init *DagRecTy::convertValue(UnOpInit *BO) {
331 if (BO->getOpcode() == UnOpInit::CAST) {
332 Init *L = BO->getOperand()->convertInitializerTo(this);
333 if (L == 0) return 0;
334 if (L != BO->getOperand())
335 return UnOpInit::get(UnOpInit::CAST, L, new DagRecTy);
341 Init *DagRecTy::convertValue(BinOpInit *BO) {
342 if (BO->getOpcode() == BinOpInit::CONCAT) {
343 Init *L = BO->getLHS()->convertInitializerTo(this);
344 Init *R = BO->getRHS()->convertInitializerTo(this);
345 if (L == 0 || R == 0) return 0;
346 if (L != BO->getLHS() || R != BO->getRHS())
347 return BinOpInit::get(BinOpInit::CONCAT, L, R, new DagRecTy);
353 RecordRecTy *RecordRecTy::get(Record *R) {
354 return &dynamic_cast<RecordRecTy&>(*R->getDefInit()->getType());
357 std::string RecordRecTy::getAsString() const {
358 return Rec->getName();
361 Init *RecordRecTy::convertValue(DefInit *DI) {
362 // Ensure that DI is a subclass of Rec.
363 if (!DI->getDef()->isSubClassOf(Rec))
368 Init *RecordRecTy::convertValue(TypedInit *TI) {
369 // Ensure that TI is compatible with Rec.
370 if (RecordRecTy *RRT = dynamic_cast<RecordRecTy*>(TI->getType()))
371 if (RRT->getRecord()->isSubClassOf(getRecord()) ||
372 RRT->getRecord() == getRecord())
377 bool RecordRecTy::baseClassOf(const RecordRecTy *RHS) const {
378 if (Rec == RHS->getRecord() || RHS->getRecord()->isSubClassOf(Rec))
381 const std::vector<Record*> &SC = Rec->getSuperClasses();
382 for (unsigned i = 0, e = SC.size(); i != e; ++i)
383 if (RHS->getRecord()->isSubClassOf(SC[i]))
390 /// resolveTypes - Find a common type that T1 and T2 convert to.
391 /// Return 0 if no such type exists.
393 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
394 if (!T1->typeIsConvertibleTo(T2)) {
395 if (!T2->typeIsConvertibleTo(T1)) {
396 // If one is a Record type, check superclasses
397 RecordRecTy *RecTy1 = dynamic_cast<RecordRecTy*>(T1);
399 // See if T2 inherits from a type T1 also inherits from
400 const std::vector<Record *> &T1SuperClasses =
401 RecTy1->getRecord()->getSuperClasses();
402 for(std::vector<Record *>::const_iterator i = T1SuperClasses.begin(),
403 iend = T1SuperClasses.end();
406 RecordRecTy *SuperRecTy1 = RecordRecTy::get(*i);
407 RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
409 if (NewType1 != SuperRecTy1) {
416 RecordRecTy *RecTy2 = dynamic_cast<RecordRecTy*>(T2);
418 // See if T1 inherits from a type T2 also inherits from
419 const std::vector<Record *> &T2SuperClasses =
420 RecTy2->getRecord()->getSuperClasses();
421 for (std::vector<Record *>::const_iterator i = T2SuperClasses.begin(),
422 iend = T2SuperClasses.end();
425 RecordRecTy *SuperRecTy2 = RecordRecTy::get(*i);
426 RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
428 if (NewType2 != SuperRecTy2) {
443 //===----------------------------------------------------------------------===//
444 // Initializer implementations
445 //===----------------------------------------------------------------------===//
447 void Init::dump() const { return print(errs()); }
449 UnsetInit *UnsetInit::get() {
450 static UnsetInit TheInit;
454 BitInit *BitInit::get(bool V) {
455 static BitInit True(true);
456 static BitInit False(false);
458 return V ? &True : &False;
462 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
463 ID.AddInteger(Range.size());
465 for (ArrayRef<Init *>::iterator i = Range.begin(),
472 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
473 typedef FoldingSet<BitsInit> Pool;
477 ProfileBitsInit(ID, Range);
480 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
483 BitsInit *I = new BitsInit(Range);
484 ThePool.InsertNode(I, IP);
489 void BitsInit::Profile(FoldingSetNodeID &ID) const {
490 ProfileBitsInit(ID, Bits);
494 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
495 SmallVector<Init *, 16> NewBits(Bits.size());
497 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
498 if (Bits[i] >= getNumBits())
500 NewBits[i] = getBit(Bits[i]);
502 return BitsInit::get(NewBits);
505 std::string BitsInit::getAsString() const {
506 std::string Result = "{ ";
507 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
508 if (i) Result += ", ";
509 if (Init *Bit = getBit(e-i-1))
510 Result += Bit->getAsString();
514 return Result + " }";
517 // resolveReferences - If there are any field references that refer to fields
518 // that have been filled in, we can propagate the values now.
520 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
521 bool Changed = false;
522 SmallVector<Init *, 16> NewBits(getNumBits());
524 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
526 Init *CurBit = getBit(i);
530 CurBit = CurBit->resolveReferences(R, RV);
531 Changed |= B != CurBit;
532 } while (B != CurBit);
537 return BitsInit::get(NewBits);
539 return const_cast<BitsInit *>(this);
542 IntInit *IntInit::get(int64_t V) {
543 typedef DenseMap<int64_t, IntInit *> Pool;
546 IntInit *&I = ThePool[V];
547 if (!I) I = new IntInit(V);
551 std::string IntInit::getAsString() const {
552 return itostr(Value);
556 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
557 SmallVector<Init *, 16> NewBits(Bits.size());
559 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
563 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
565 return BitsInit::get(NewBits);
568 StringInit *StringInit::get(const std::string &V) {
569 typedef StringMap<StringInit *> Pool;
572 StringInit *&I = ThePool[V];
573 if (!I) I = new StringInit(V);
577 CodeInit *CodeInit::get(const std::string &V) {
578 typedef StringMap<CodeInit *> Pool;
581 CodeInit *&I = ThePool[V];
582 if (!I) I = new CodeInit(V);
586 static void ProfileListInit(FoldingSetNodeID &ID,
587 ArrayRef<Init *> Range,
589 ID.AddInteger(Range.size());
590 ID.AddPointer(EltTy);
592 for (ArrayRef<Init *>::iterator i = Range.begin(),
599 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
600 typedef FoldingSet<ListInit> Pool;
603 // Just use the FoldingSetNodeID to compute a hash. Use a DenseMap
604 // for actual storage.
606 ProfileListInit(ID, Range, EltTy);
609 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
612 ListInit *I = new ListInit(Range, EltTy);
613 ThePool.InsertNode(I, IP);
617 void ListInit::Profile(FoldingSetNodeID &ID) const {
618 ListRecTy *ListType = dynamic_cast<ListRecTy *>(getType());
619 assert(ListType && "Bad type for ListInit!");
620 RecTy *EltTy = ListType->getElementType();
622 ProfileListInit(ID, Values, EltTy);
626 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
627 std::vector<Init*> Vals;
628 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
629 if (Elements[i] >= getSize())
631 Vals.push_back(getElement(Elements[i]));
633 return ListInit::get(Vals, getType());
636 Record *ListInit::getElementAsRecord(unsigned i) const {
637 assert(i < Values.size() && "List element index out of range!");
638 DefInit *DI = dynamic_cast<DefInit*>(Values[i]);
639 if (DI == 0) throw "Expected record in list!";
643 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
644 std::vector<Init*> Resolved;
645 Resolved.reserve(getSize());
646 bool Changed = false;
648 for (unsigned i = 0, e = getSize(); i != e; ++i) {
650 Init *CurElt = getElement(i);
654 CurElt = CurElt->resolveReferences(R, RV);
655 Changed |= E != CurElt;
656 } while (E != CurElt);
657 Resolved.push_back(E);
661 return ListInit::get(Resolved, getType());
662 return const_cast<ListInit *>(this);
665 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
666 unsigned Elt) const {
667 if (Elt >= getSize())
668 return 0; // Out of range reference.
669 Init *E = getElement(Elt);
670 // If the element is set to some value, or if we are resolving a reference
671 // to a specific variable and that variable is explicitly unset, then
672 // replace the VarListElementInit with it.
673 if (IRV || !dynamic_cast<UnsetInit*>(E))
678 std::string ListInit::getAsString() const {
679 std::string Result = "[";
680 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
681 if (i) Result += ", ";
682 Result += Values[i]->getAsString();
687 Init *OpInit::resolveBitReference(Record &R, const RecordVal *IRV,
688 unsigned Bit) const {
689 Init *Folded = Fold(&R, 0);
691 if (Folded != this) {
692 TypedInit *Typed = dynamic_cast<TypedInit *>(Folded);
694 return Typed->resolveBitReference(R, IRV, Bit);
701 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
702 unsigned Elt) const {
703 Init *Resolved = resolveReferences(R, IRV);
704 OpInit *OResolved = dynamic_cast<OpInit *>(Resolved);
706 Resolved = OResolved->Fold(&R, 0);
709 if (Resolved != this) {
710 TypedInit *Typed = dynamic_cast<TypedInit *>(Resolved);
711 assert(Typed && "Expected typed init for list reference");
713 Init *New = Typed->resolveListElementReference(R, IRV, Elt);
716 return VarListElementInit::get(Typed, Elt);
723 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
724 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
726 typedef DenseMap<Key, UnOpInit *> Pool;
729 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
731 UnOpInit *&I = ThePool[TheKey];
732 if (!I) I = new UnOpInit(opc, lhs, Type);
736 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
737 switch (getOpcode()) {
738 default: assert(0 && "Unknown unop");
740 if (getType()->getAsString() == "string") {
741 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
746 DefInit *LHSd = dynamic_cast<DefInit*>(LHS);
748 return StringInit::get(LHSd->getDef()->getName());
751 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
753 std::string Name = LHSs->getValue();
755 // From TGParser::ParseIDValue
757 if (const RecordVal *RV = CurRec->getValue(Name)) {
758 if (RV->getType() != getType())
759 throw "type mismatch in cast";
760 return VarInit::get(Name, RV->getType());
763 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
766 if (CurRec->isTemplateArg(TemplateArgName)) {
767 const RecordVal *RV = CurRec->getValue(TemplateArgName);
768 assert(RV && "Template arg doesn't exist??");
770 if (RV->getType() != getType())
771 throw "type mismatch in cast";
773 return VarInit::get(TemplateArgName, RV->getType());
778 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
780 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
781 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
782 assert(RV && "Template arg doesn't exist??");
784 if (RV->getType() != getType())
785 throw "type mismatch in cast";
787 return VarInit::get(MCName, RV->getType());
791 if (Record *D = (CurRec->getRecords()).getDef(Name))
792 return DefInit::get(D);
794 throw TGError(CurRec->getLoc(), "Undefined reference:'" + Name + "'\n");
800 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
802 if (LHSl->getSize() == 0) {
803 assert(0 && "Empty list in car");
806 return LHSl->getElement(0);
811 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
813 if (LHSl->getSize() == 0) {
814 assert(0 && "Empty list in cdr");
817 // Note the +1. We can't just pass the result of getValues()
819 ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
820 ArrayRef<Init *>::iterator end = LHSl->getValues().end();
822 ListInit::get(ArrayRef<Init *>(begin, end - begin),
829 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
831 if (LHSl->getSize() == 0) {
832 return IntInit::get(1);
834 return IntInit::get(0);
837 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
839 if (LHSs->getValue().empty()) {
840 return IntInit::get(1);
842 return IntInit::get(0);
849 return const_cast<UnOpInit *>(this);
852 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
853 Init *lhs = LHS->resolveReferences(R, RV);
856 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, 0);
860 std::string UnOpInit::getAsString() const {
863 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
864 case HEAD: Result = "!head"; break;
865 case TAIL: Result = "!tail"; break;
866 case EMPTY: Result = "!empty"; break;
868 return Result + "(" + LHS->getAsString() + ")";
871 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
872 Init *rhs, RecTy *Type) {
874 std::pair<std::pair<unsigned, Init *>, Init *>,
878 typedef DenseMap<Key, BinOpInit *> Pool;
881 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
884 BinOpInit *&I = ThePool[TheKey];
885 if (!I) I = new BinOpInit(opc, lhs, rhs, Type);
889 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
890 switch (getOpcode()) {
891 default: assert(0 && "Unknown binop");
893 DagInit *LHSs = dynamic_cast<DagInit*>(LHS);
894 DagInit *RHSs = dynamic_cast<DagInit*>(RHS);
896 DefInit *LOp = dynamic_cast<DefInit*>(LHSs->getOperator());
897 DefInit *ROp = dynamic_cast<DefInit*>(RHSs->getOperator());
898 if (LOp == 0 || ROp == 0 || LOp->getDef() != ROp->getDef())
899 throw "Concated Dag operators do not match!";
900 std::vector<Init*> Args;
901 std::vector<std::string> ArgNames;
902 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
903 Args.push_back(LHSs->getArg(i));
904 ArgNames.push_back(LHSs->getArgName(i));
906 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
907 Args.push_back(RHSs->getArg(i));
908 ArgNames.push_back(RHSs->getArgName(i));
910 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
915 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
916 StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
918 return StringInit::get(LHSs->getValue() + RHSs->getValue());
922 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
923 // to string objects.
925 dynamic_cast<IntInit*>(LHS->convertInitializerTo(IntRecTy::get()));
927 dynamic_cast<IntInit*>(RHS->convertInitializerTo(IntRecTy::get()));
930 return IntInit::get(L->getValue() == R->getValue());
932 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
933 StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
935 // Make sure we've resolved
937 return IntInit::get(LHSs->getValue() == RHSs->getValue());
944 IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
945 IntInit *RHSi = dynamic_cast<IntInit*>(RHS);
947 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
949 switch (getOpcode()) {
950 default: assert(0 && "Bad opcode!");
951 case SHL: Result = LHSv << RHSv; break;
952 case SRA: Result = LHSv >> RHSv; break;
953 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
955 return IntInit::get(Result);
960 return const_cast<BinOpInit *>(this);
963 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
964 Init *lhs = LHS->resolveReferences(R, RV);
965 Init *rhs = RHS->resolveReferences(R, RV);
967 if (LHS != lhs || RHS != rhs)
968 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R, 0);
972 std::string BinOpInit::getAsString() const {
975 case CONCAT: Result = "!con"; break;
976 case SHL: Result = "!shl"; break;
977 case SRA: Result = "!sra"; break;
978 case SRL: Result = "!srl"; break;
979 case EQ: Result = "!eq"; break;
980 case STRCONCAT: Result = "!strconcat"; break;
982 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
985 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs,
986 Init *mhs, Init *rhs,
990 std::pair<std::pair<unsigned, RecTy *>, Init *>,
996 typedef DenseMap<Key, TernOpInit *> Pool;
999 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
1005 TernOpInit *&I = ThePool[TheKey];
1006 if (!I) I = new TernOpInit(opc, lhs, mhs, rhs, Type);
1010 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1011 Record *CurRec, MultiClass *CurMultiClass);
1013 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
1014 RecTy *Type, Record *CurRec,
1015 MultiClass *CurMultiClass) {
1016 std::vector<Init *> NewOperands;
1018 TypedInit *TArg = dynamic_cast<TypedInit*>(Arg);
1020 // If this is a dag, recurse
1021 if (TArg && TArg->getType()->getAsString() == "dag") {
1022 Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
1023 CurRec, CurMultiClass);
1031 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
1032 OpInit *RHSoo = dynamic_cast<OpInit*>(RHSo->getOperand(i));
1035 Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1036 Type, CurRec, CurMultiClass);
1038 NewOperands.push_back(Result);
1040 NewOperands.push_back(Arg);
1042 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1043 NewOperands.push_back(Arg);
1045 NewOperands.push_back(RHSo->getOperand(i));
1049 // Now run the operator and use its result as the new leaf
1050 const OpInit *NewOp = RHSo->clone(NewOperands);
1051 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
1052 if (NewVal != NewOp)
1058 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1059 Record *CurRec, MultiClass *CurMultiClass) {
1060 DagInit *MHSd = dynamic_cast<DagInit*>(MHS);
1061 ListInit *MHSl = dynamic_cast<ListInit*>(MHS);
1063 DagRecTy *DagType = dynamic_cast<DagRecTy*>(Type);
1064 ListRecTy *ListType = dynamic_cast<ListRecTy*>(Type);
1066 OpInit *RHSo = dynamic_cast<OpInit*>(RHS);
1069 throw TGError(CurRec->getLoc(), "!foreach requires an operator\n");
1072 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
1075 throw TGError(CurRec->getLoc(), "!foreach requires typed variable\n");
1078 if ((MHSd && DagType) || (MHSl && ListType)) {
1080 Init *Val = MHSd->getOperator();
1081 Init *Result = EvaluateOperation(RHSo, LHS, Val,
1082 Type, CurRec, CurMultiClass);
1087 std::vector<std::pair<Init *, std::string> > args;
1088 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1090 std::string ArgName;
1091 Arg = MHSd->getArg(i);
1092 ArgName = MHSd->getArgName(i);
1095 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1096 CurRec, CurMultiClass);
1101 // TODO: Process arg names
1102 args.push_back(std::make_pair(Arg, ArgName));
1105 return DagInit::get(Val, "", args);
1108 std::vector<Init *> NewOperands;
1109 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1111 for (std::vector<Init *>::iterator li = NewList.begin(),
1112 liend = NewList.end();
1116 NewOperands.clear();
1117 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1118 // First, replace the foreach variable with the list item
1119 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1120 NewOperands.push_back(Item);
1122 NewOperands.push_back(RHSo->getOperand(i));
1126 // Now run the operator and use its result as the new list item
1127 const OpInit *NewOp = RHSo->clone(NewOperands);
1128 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1129 if (NewItem != NewOp)
1132 return ListInit::get(NewList, MHSl->getType());
1138 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1139 switch (getOpcode()) {
1140 default: assert(0 && "Unknown binop");
1142 DefInit *LHSd = dynamic_cast<DefInit*>(LHS);
1143 VarInit *LHSv = dynamic_cast<VarInit*>(LHS);
1144 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
1146 DefInit *MHSd = dynamic_cast<DefInit*>(MHS);
1147 VarInit *MHSv = dynamic_cast<VarInit*>(MHS);
1148 StringInit *MHSs = dynamic_cast<StringInit*>(MHS);
1150 DefInit *RHSd = dynamic_cast<DefInit*>(RHS);
1151 VarInit *RHSv = dynamic_cast<VarInit*>(RHS);
1152 StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
1154 if ((LHSd && MHSd && RHSd)
1155 || (LHSv && MHSv && RHSv)
1156 || (LHSs && MHSs && RHSs)) {
1158 Record *Val = RHSd->getDef();
1159 if (LHSd->getAsString() == RHSd->getAsString()) {
1160 Val = MHSd->getDef();
1162 return DefInit::get(Val);
1165 std::string Val = RHSv->getName();
1166 if (LHSv->getAsString() == RHSv->getAsString()) {
1167 Val = MHSv->getName();
1169 return VarInit::get(Val, getType());
1172 std::string Val = RHSs->getValue();
1174 std::string::size_type found;
1175 std::string::size_type idx = 0;
1177 found = Val.find(LHSs->getValue(), idx);
1178 if (found != std::string::npos) {
1179 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1181 idx = found + MHSs->getValue().size();
1182 } while (found != std::string::npos);
1184 return StringInit::get(Val);
1191 Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1192 CurRec, CurMultiClass);
1200 IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
1201 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1202 LHSi = dynamic_cast<IntInit*>(I);
1204 if (LHSi->getValue()) {
1214 return const_cast<TernOpInit *>(this);
1217 Init *TernOpInit::resolveReferences(Record &R,
1218 const RecordVal *RV) const {
1219 Init *lhs = LHS->resolveReferences(R, RV);
1221 if (Opc == IF && lhs != LHS) {
1222 IntInit *Value = dynamic_cast<IntInit*>(lhs);
1223 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1224 Value = dynamic_cast<IntInit*>(I);
1227 if (Value->getValue()) {
1228 Init *mhs = MHS->resolveReferences(R, RV);
1229 return (TernOpInit::get(getOpcode(), lhs, mhs,
1230 RHS, getType()))->Fold(&R, 0);
1232 Init *rhs = RHS->resolveReferences(R, RV);
1233 return (TernOpInit::get(getOpcode(), lhs, MHS,
1234 rhs, getType()))->Fold(&R, 0);
1239 Init *mhs = MHS->resolveReferences(R, RV);
1240 Init *rhs = RHS->resolveReferences(R, RV);
1242 if (LHS != lhs || MHS != mhs || RHS != rhs)
1243 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1244 getType()))->Fold(&R, 0);
1248 std::string TernOpInit::getAsString() const {
1251 case SUBST: Result = "!subst"; break;
1252 case FOREACH: Result = "!foreach"; break;
1253 case IF: Result = "!if"; break;
1255 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
1256 + RHS->getAsString() + ")";
1259 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1260 RecordRecTy *RecordType = dynamic_cast<RecordRecTy *>(getType());
1262 RecordVal *Field = RecordType->getRecord()->getValue(FieldName);
1264 return Field->getType();
1271 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1272 BitsRecTy *T = dynamic_cast<BitsRecTy*>(getType());
1273 if (T == 0) return 0; // Cannot subscript a non-bits variable.
1274 unsigned NumBits = T->getNumBits();
1276 SmallVector<Init *, 16> NewBits(Bits.size());
1277 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1278 if (Bits[i] >= NumBits)
1281 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1283 return BitsInit::get(NewBits);
1287 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1288 ListRecTy *T = dynamic_cast<ListRecTy*>(getType());
1289 if (T == 0) return 0; // Cannot subscript a non-list variable.
1291 if (Elements.size() == 1)
1292 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1294 std::vector<Init*> ListInits;
1295 ListInits.reserve(Elements.size());
1296 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1297 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1299 return ListInit::get(ListInits, T);
1303 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1304 Init *Value = StringInit::get(VN);
1305 return VarInit::get(Value, T);
1308 VarInit *VarInit::get(Init *VN, RecTy *T) {
1309 typedef std::pair<RecTy *, Init *> Key;
1310 typedef DenseMap<Key, VarInit *> Pool;
1311 static Pool ThePool;
1313 Key TheKey(std::make_pair(T, VN));
1315 VarInit *&I = ThePool[TheKey];
1316 if (!I) I = new VarInit(VN, T);
1320 const std::string &VarInit::getName() const {
1321 StringInit *NameString =
1322 dynamic_cast<StringInit *>(getNameInit());
1323 assert(NameString && "VarInit name is not a string!");
1324 return NameString->getValue();
1327 Init *VarInit::resolveBitReference(Record &R, const RecordVal *IRV,
1328 unsigned Bit) const {
1329 if (R.isTemplateArg(getName())) return 0;
1330 if (IRV && IRV->getName() != getName()) return 0;
1332 RecordVal *RV = R.getValue(getName());
1333 assert(RV && "Reference to a non-existent variable?");
1334 assert(dynamic_cast<BitsInit*>(RV->getValue()));
1335 BitsInit *BI = (BitsInit*)RV->getValue();
1337 assert(Bit < BI->getNumBits() && "Bit reference out of range!");
1338 Init *B = BI->getBit(Bit);
1340 // If the bit is set to some value, or if we are resolving a reference to a
1341 // specific variable and that variable is explicitly unset, then replace the
1342 // VarBitInit with it.
1343 if (IRV || !dynamic_cast<UnsetInit*>(B))
1348 Init *VarInit::resolveListElementReference(Record &R,
1349 const RecordVal *IRV,
1350 unsigned Elt) const {
1351 if (R.isTemplateArg(getName())) return 0;
1352 if (IRV && IRV->getName() != getName()) return 0;
1354 RecordVal *RV = R.getValue(getName());
1355 assert(RV && "Reference to a non-existent variable?");
1356 ListInit *LI = dynamic_cast<ListInit*>(RV->getValue());
1358 TypedInit *VI = dynamic_cast<TypedInit*>(RV->getValue());
1359 assert(VI && "Invalid list element!");
1360 return VarListElementInit::get(VI, Elt);
1363 if (Elt >= LI->getSize())
1364 return 0; // Out of range reference.
1365 Init *E = LI->getElement(Elt);
1366 // If the element is set to some value, or if we are resolving a reference
1367 // to a specific variable and that variable is explicitly unset, then
1368 // replace the VarListElementInit with it.
1369 if (IRV || !dynamic_cast<UnsetInit*>(E))
1375 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1376 if (RecordRecTy *RTy = dynamic_cast<RecordRecTy*>(getType()))
1377 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1378 return RV->getType();
1382 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1383 const std::string &FieldName) const {
1384 if (dynamic_cast<RecordRecTy*>(getType()))
1385 if (const RecordVal *Val = R.getValue(VarName)) {
1386 if (RV != Val && (RV || dynamic_cast<UnsetInit*>(Val->getValue())))
1388 Init *TheInit = Val->getValue();
1389 assert(TheInit != this && "Infinite loop detected!");
1390 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1398 /// resolveReferences - This method is used by classes that refer to other
1399 /// variables which may not be defined at the time the expression is formed.
1400 /// If a value is set for the variable later, this method will be called on
1401 /// users of the value to allow the value to propagate out.
1403 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1404 if (RecordVal *Val = R.getValue(VarName))
1405 if (RV == Val || (RV == 0 && !dynamic_cast<UnsetInit*>(Val->getValue())))
1406 return Val->getValue();
1407 return const_cast<VarInit *>(this);
1410 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1411 typedef std::pair<TypedInit *, unsigned> Key;
1412 typedef DenseMap<Key, VarBitInit *> Pool;
1414 static Pool ThePool;
1416 Key TheKey(std::make_pair(T, B));
1418 VarBitInit *&I = ThePool[TheKey];
1419 if (!I) I = new VarBitInit(T, B);
1423 std::string VarBitInit::getAsString() const {
1424 return TI->getAsString() + "{" + utostr(Bit) + "}";
1427 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1428 if (Init *I = getVariable()->resolveBitReference(R, RV, getBitNum()))
1430 return const_cast<VarBitInit *>(this);
1433 VarListElementInit *VarListElementInit::get(TypedInit *T,
1435 typedef std::pair<TypedInit *, unsigned> Key;
1436 typedef DenseMap<Key, VarListElementInit *> Pool;
1438 static Pool ThePool;
1440 Key TheKey(std::make_pair(T, E));
1442 VarListElementInit *&I = ThePool[TheKey];
1443 if (!I) I = new VarListElementInit(T, E);
1447 std::string VarListElementInit::getAsString() const {
1448 return TI->getAsString() + "[" + utostr(Element) + "]";
1452 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1453 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1456 return const_cast<VarListElementInit *>(this);
1459 Init *VarListElementInit::resolveBitReference(Record &R, const RecordVal *RV,
1460 unsigned Bit) const {
1461 // FIXME: This should be implemented, to support references like:
1462 // bit B = AA[0]{1};
1466 Init *VarListElementInit:: resolveListElementReference(Record &R,
1467 const RecordVal *RV,
1468 unsigned Elt) const {
1469 Init *Result = TI->resolveListElementReference(R, RV, Element);
1472 TypedInit *TInit = dynamic_cast<TypedInit *>(Result);
1474 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1475 if (Result2) return Result2;
1476 return new VarListElementInit(TInit, Elt);
1484 DefInit *DefInit::get(Record *R) {
1485 return R->getDefInit();
1488 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1489 if (const RecordVal *RV = Def->getValue(FieldName))
1490 return RV->getType();
1494 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1495 const std::string &FieldName) const {
1496 return Def->getValue(FieldName)->getValue();
1500 std::string DefInit::getAsString() const {
1501 return Def->getName();
1504 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1505 typedef std::pair<Init *, TableGenStringKey> Key;
1506 typedef DenseMap<Key, FieldInit *> Pool;
1507 static Pool ThePool;
1509 Key TheKey(std::make_pair(R, FN));
1511 FieldInit *&I = ThePool[TheKey];
1512 if (!I) I = new FieldInit(R, FN);
1516 Init *FieldInit::resolveBitReference(Record &R, const RecordVal *RV,
1517 unsigned Bit) const {
1518 if (Init *BitsVal = Rec->getFieldInit(R, RV, FieldName))
1519 if (BitsInit *BI = dynamic_cast<BitsInit*>(BitsVal)) {
1520 assert(Bit < BI->getNumBits() && "Bit reference out of range!");
1521 Init *B = BI->getBit(Bit);
1523 if (dynamic_cast<BitInit*>(B)) // If the bit is set.
1524 return B; // Replace the VarBitInit with it.
1529 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1530 unsigned Elt) const {
1531 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1532 if (ListInit *LI = dynamic_cast<ListInit*>(ListVal)) {
1533 if (Elt >= LI->getSize()) return 0;
1534 Init *E = LI->getElement(Elt);
1536 // If the element is set to some value, or if we are resolving a
1537 // reference to a specific variable and that variable is explicitly
1538 // unset, then replace the VarListElementInit with it.
1539 if (RV || !dynamic_cast<UnsetInit*>(E))
1545 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1546 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1548 Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1550 Init *BVR = BitsVal->resolveReferences(R, RV);
1551 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1554 if (NewRec != Rec) {
1555 return FieldInit::get(NewRec, FieldName);
1557 return const_cast<FieldInit *>(this);
1560 void ProfileDagInit(FoldingSetNodeID &ID,
1562 const std::string &VN,
1563 ArrayRef<Init *> ArgRange,
1564 ArrayRef<std::string> NameRange) {
1568 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1569 ArrayRef<std::string>::iterator Name = NameRange.begin();
1570 while (Arg != ArgRange.end()) {
1571 assert(Name != NameRange.end() && "Arg name underflow!");
1572 ID.AddPointer(*Arg++);
1573 ID.AddString(*Name++);
1575 assert(Name == NameRange.end() && "Arg name overflow!");
1579 DagInit::get(Init *V, const std::string &VN,
1580 ArrayRef<Init *> ArgRange,
1581 ArrayRef<std::string> NameRange) {
1582 typedef FoldingSet<DagInit> Pool;
1583 static Pool ThePool;
1585 FoldingSetNodeID ID;
1586 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1589 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1592 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1593 ThePool.InsertNode(I, IP);
1599 DagInit::get(Init *V, const std::string &VN,
1600 const std::vector<std::pair<Init*, std::string> > &args) {
1601 typedef std::pair<Init*, std::string> PairType;
1603 std::vector<Init *> Args;
1604 std::vector<std::string> Names;
1606 for (std::vector<PairType>::const_iterator i = args.begin(),
1610 Args.push_back(i->first);
1611 Names.push_back(i->second);
1614 return DagInit::get(V, VN, Args, Names);
1617 void DagInit::Profile(FoldingSetNodeID &ID) const {
1618 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1621 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1622 std::vector<Init*> NewArgs;
1623 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1624 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1626 Init *Op = Val->resolveReferences(R, RV);
1628 if (Args != NewArgs || Op != Val)
1629 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1631 return const_cast<DagInit *>(this);
1635 std::string DagInit::getAsString() const {
1636 std::string Result = "(" + Val->getAsString();
1637 if (!ValName.empty())
1638 Result += ":" + ValName;
1640 Result += " " + Args[0]->getAsString();
1641 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1642 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1643 Result += ", " + Args[i]->getAsString();
1644 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1647 return Result + ")";
1651 //===----------------------------------------------------------------------===//
1652 // Other implementations
1653 //===----------------------------------------------------------------------===//
1655 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1656 : Name(N), Ty(T), Prefix(P) {
1657 Value = Ty->convertValue(UnsetInit::get());
1658 assert(Value && "Cannot create unset value for current type!");
1661 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1662 : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1663 Value = Ty->convertValue(UnsetInit::get());
1664 assert(Value && "Cannot create unset value for current type!");
1667 const std::string &RecordVal::getName() const {
1668 StringInit *NameString = dynamic_cast<StringInit *>(Name);
1669 assert(NameString && "RecordVal name is not a string!");
1670 return NameString->getValue();
1673 void RecordVal::dump() const { errs() << *this; }
1675 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1676 if (getPrefix()) OS << "field ";
1677 OS << *getType() << " " << getName();
1680 OS << " = " << *getValue();
1682 if (PrintSem) OS << ";\n";
1685 unsigned Record::LastID = 0;
1687 void Record::checkName() {
1688 // Ensure the record name has string type.
1689 const TypedInit *TypedName = dynamic_cast<const TypedInit *>(Name);
1690 assert(TypedName && "Record name is not typed!");
1691 RecTy *Type = TypedName->getType();
1692 if (dynamic_cast<StringRecTy *>(Type) == 0) {
1693 llvm_unreachable("Record name is not a string!");
1697 DefInit *Record::getDefInit() {
1699 TheInit = new DefInit(this, new RecordRecTy(this));
1703 const std::string &Record::getName() const {
1704 const StringInit *NameString =
1705 dynamic_cast<const StringInit *>(Name);
1706 assert(NameString && "Record name is not a string!");
1707 return NameString->getValue();
1710 void Record::setName(Init *NewName) {
1711 if (TrackedRecords.getDef(Name->getAsUnquotedString()) == this) {
1712 TrackedRecords.removeDef(Name->getAsUnquotedString());
1714 TrackedRecords.addDef(this);
1716 TrackedRecords.removeClass(Name->getAsUnquotedString());
1718 TrackedRecords.addClass(this);
1721 // Since the Init for the name was changed, see if we can resolve
1722 // any of it using members of the Record.
1723 Init *ComputedName = Name->resolveReferences(*this, 0);
1724 if (ComputedName != Name) {
1725 setName(ComputedName);
1727 // DO NOT resolve record values to the name at this point because
1728 // there might be default values for arguments of this def. Those
1729 // arguments might not have been resolved yet so we don't want to
1730 // prematurely assume values for those arguments were not passed to
1733 // Nonetheless, it may be that some of this Record's values
1734 // reference the record name. Indeed, the reason for having the
1735 // record name be an Init is to provide this flexibility. The extra
1736 // resolve steps after completely instantiating defs takes care of
1737 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1740 void Record::setName(const std::string &Name) {
1741 setName(StringInit::get(Name));
1744 const RecordVal *Record::getValue(Init *Name) const {
1745 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1746 if (Values[i].getNameInit() == Name) return &Values[i];
1750 RecordVal *Record::getValue(Init *Name) {
1751 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1752 if (Values[i].getNameInit() == Name) return &Values[i];
1756 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1757 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1759 void Record::resolveReferencesTo(const RecordVal *RV) {
1760 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1761 if (Init *V = Values[i].getValue())
1762 Values[i].setValue(V->resolveReferences(*this, RV));
1766 void Record::dump() const { errs() << *this; }
1768 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1771 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1772 if (!TArgs.empty()) {
1774 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1776 const RecordVal *RV = R.getValue(TArgs[i]);
1777 assert(RV && "Template argument record not found??");
1778 RV->print(OS, false);
1784 const std::vector<Record*> &SC = R.getSuperClasses();
1787 for (unsigned i = 0, e = SC.size(); i != e; ++i)
1788 OS << " " << SC[i]->getName();
1792 const std::vector<RecordVal> &Vals = R.getValues();
1793 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1794 if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1796 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1797 if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1803 /// getValueInit - Return the initializer for a value with the specified name,
1804 /// or throw an exception if the field does not exist.
1806 Init *Record::getValueInit(StringRef FieldName) const {
1807 const RecordVal *R = getValue(FieldName);
1808 if (R == 0 || R->getValue() == 0)
1809 throw "Record `" + getName() + "' does not have a field named `" +
1810 FieldName.str() + "'!\n";
1811 return R->getValue();
1815 /// getValueAsString - This method looks up the specified field and returns its
1816 /// value as a string, throwing an exception if the field does not exist or if
1817 /// the value is not a string.
1819 std::string Record::getValueAsString(StringRef FieldName) const {
1820 const RecordVal *R = getValue(FieldName);
1821 if (R == 0 || R->getValue() == 0)
1822 throw "Record `" + getName() + "' does not have a field named `" +
1823 FieldName.str() + "'!\n";
1825 if (StringInit *SI = dynamic_cast<StringInit*>(R->getValue()))
1826 return SI->getValue();
1827 throw "Record `" + getName() + "', field `" + FieldName.str() +
1828 "' does not have a string initializer!";
1831 /// getValueAsBitsInit - This method looks up the specified field and returns
1832 /// its value as a BitsInit, throwing an exception if the field does not exist
1833 /// or if the value is not the right type.
1835 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1836 const RecordVal *R = getValue(FieldName);
1837 if (R == 0 || R->getValue() == 0)
1838 throw "Record `" + getName() + "' does not have a field named `" +
1839 FieldName.str() + "'!\n";
1841 if (BitsInit *BI = dynamic_cast<BitsInit*>(R->getValue()))
1843 throw "Record `" + getName() + "', field `" + FieldName.str() +
1844 "' does not have a BitsInit initializer!";
1847 /// getValueAsListInit - This method looks up the specified field and returns
1848 /// its value as a ListInit, throwing an exception if the field does not exist
1849 /// or if the value is not the right type.
1851 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1852 const RecordVal *R = getValue(FieldName);
1853 if (R == 0 || R->getValue() == 0)
1854 throw "Record `" + getName() + "' does not have a field named `" +
1855 FieldName.str() + "'!\n";
1857 if (ListInit *LI = dynamic_cast<ListInit*>(R->getValue()))
1859 throw "Record `" + getName() + "', field `" + FieldName.str() +
1860 "' does not have a list initializer!";
1863 /// getValueAsListOfDefs - This method looks up the specified field and returns
1864 /// its value as a vector of records, throwing an exception if the field does
1865 /// not exist or if the value is not the right type.
1867 std::vector<Record*>
1868 Record::getValueAsListOfDefs(StringRef FieldName) const {
1869 ListInit *List = getValueAsListInit(FieldName);
1870 std::vector<Record*> Defs;
1871 for (unsigned i = 0; i < List->getSize(); i++) {
1872 if (DefInit *DI = dynamic_cast<DefInit*>(List->getElement(i))) {
1873 Defs.push_back(DI->getDef());
1875 throw "Record `" + getName() + "', field `" + FieldName.str() +
1876 "' list is not entirely DefInit!";
1882 /// getValueAsInt - This method looks up the specified field and returns its
1883 /// value as an int64_t, throwing an exception if the field does not exist or if
1884 /// the value is not the right type.
1886 int64_t Record::getValueAsInt(StringRef FieldName) const {
1887 const RecordVal *R = getValue(FieldName);
1888 if (R == 0 || R->getValue() == 0)
1889 throw "Record `" + getName() + "' does not have a field named `" +
1890 FieldName.str() + "'!\n";
1892 if (IntInit *II = dynamic_cast<IntInit*>(R->getValue()))
1893 return II->getValue();
1894 throw "Record `" + getName() + "', field `" + FieldName.str() +
1895 "' does not have an int initializer!";
1898 /// getValueAsListOfInts - This method looks up the specified field and returns
1899 /// its value as a vector of integers, throwing an exception if the field does
1900 /// not exist or if the value is not the right type.
1902 std::vector<int64_t>
1903 Record::getValueAsListOfInts(StringRef FieldName) const {
1904 ListInit *List = getValueAsListInit(FieldName);
1905 std::vector<int64_t> Ints;
1906 for (unsigned i = 0; i < List->getSize(); i++) {
1907 if (IntInit *II = dynamic_cast<IntInit*>(List->getElement(i))) {
1908 Ints.push_back(II->getValue());
1910 throw "Record `" + getName() + "', field `" + FieldName.str() +
1911 "' does not have a list of ints initializer!";
1917 /// getValueAsListOfStrings - This method looks up the specified field and
1918 /// returns its value as a vector of strings, throwing an exception if the
1919 /// field does not exist or if the value is not the right type.
1921 std::vector<std::string>
1922 Record::getValueAsListOfStrings(StringRef FieldName) const {
1923 ListInit *List = getValueAsListInit(FieldName);
1924 std::vector<std::string> Strings;
1925 for (unsigned i = 0; i < List->getSize(); i++) {
1926 if (StringInit *II = dynamic_cast<StringInit*>(List->getElement(i))) {
1927 Strings.push_back(II->getValue());
1929 throw "Record `" + getName() + "', field `" + FieldName.str() +
1930 "' does not have a list of strings initializer!";
1936 /// getValueAsDef - This method looks up the specified field and returns its
1937 /// value as a Record, throwing an exception if the field does not exist or if
1938 /// the value is not the right type.
1940 Record *Record::getValueAsDef(StringRef FieldName) const {
1941 const RecordVal *R = getValue(FieldName);
1942 if (R == 0 || R->getValue() == 0)
1943 throw "Record `" + getName() + "' does not have a field named `" +
1944 FieldName.str() + "'!\n";
1946 if (DefInit *DI = dynamic_cast<DefInit*>(R->getValue()))
1947 return DI->getDef();
1948 throw "Record `" + getName() + "', field `" + FieldName.str() +
1949 "' does not have a def initializer!";
1952 /// getValueAsBit - This method looks up the specified field and returns its
1953 /// value as a bit, throwing an exception if the field does not exist or if
1954 /// the value is not the right type.
1956 bool Record::getValueAsBit(StringRef FieldName) const {
1957 const RecordVal *R = getValue(FieldName);
1958 if (R == 0 || R->getValue() == 0)
1959 throw "Record `" + getName() + "' does not have a field named `" +
1960 FieldName.str() + "'!\n";
1962 if (BitInit *BI = dynamic_cast<BitInit*>(R->getValue()))
1963 return BI->getValue();
1964 throw "Record `" + getName() + "', field `" + FieldName.str() +
1965 "' does not have a bit initializer!";
1968 /// getValueAsDag - This method looks up the specified field and returns its
1969 /// value as an Dag, throwing an exception if the field does not exist or if
1970 /// the value is not the right type.
1972 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1973 const RecordVal *R = getValue(FieldName);
1974 if (R == 0 || R->getValue() == 0)
1975 throw "Record `" + getName() + "' does not have a field named `" +
1976 FieldName.str() + "'!\n";
1978 if (DagInit *DI = dynamic_cast<DagInit*>(R->getValue()))
1980 throw "Record `" + getName() + "', field `" + FieldName.str() +
1981 "' does not have a dag initializer!";
1984 std::string Record::getValueAsCode(StringRef FieldName) const {
1985 const RecordVal *R = getValue(FieldName);
1986 if (R == 0 || R->getValue() == 0)
1987 throw "Record `" + getName() + "' does not have a field named `" +
1988 FieldName.str() + "'!\n";
1990 if (CodeInit *CI = dynamic_cast<CodeInit*>(R->getValue()))
1991 return CI->getValue();
1992 throw "Record `" + getName() + "', field `" + FieldName.str() +
1993 "' does not have a code initializer!";
1997 void MultiClass::dump() const {
1998 errs() << "Record:\n";
2001 errs() << "Defs:\n";
2002 for (RecordVector::const_iterator r = DefPrototypes.begin(),
2003 rend = DefPrototypes.end();
2011 void RecordKeeper::dump() const { errs() << *this; }
2013 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
2014 OS << "------------- Classes -----------------\n";
2015 const std::map<std::string, Record*> &Classes = RK.getClasses();
2016 for (std::map<std::string, Record*>::const_iterator I = Classes.begin(),
2017 E = Classes.end(); I != E; ++I)
2018 OS << "class " << *I->second;
2020 OS << "------------- Defs -----------------\n";
2021 const std::map<std::string, Record*> &Defs = RK.getDefs();
2022 for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),
2023 E = Defs.end(); I != E; ++I)
2024 OS << "def " << *I->second;
2029 /// getAllDerivedDefinitions - This method returns all concrete definitions
2030 /// that derive from the specified class name. If a class with the specified
2031 /// name does not exist, an error is printed and true is returned.
2032 std::vector<Record*>
2033 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
2034 Record *Class = getClass(ClassName);
2036 throw "ERROR: Couldn't find the `" + ClassName + "' class!\n";
2038 std::vector<Record*> Defs;
2039 for (std::map<std::string, Record*>::const_iterator I = getDefs().begin(),
2040 E = getDefs().end(); I != E; ++I)
2041 if (I->second->isSubClassOf(Class))
2042 Defs.push_back(I->second);
2047 /// QualifyName - Return an Init with a qualifier prefix referring
2048 /// to CurRec's name.
2049 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2050 Init *Name, const std::string &Scoper) {
2051 RecTy *Type = dynamic_cast<TypedInit *>(Name)->getType();
2053 BinOpInit *NewName =
2054 BinOpInit::get(BinOpInit::STRCONCAT,
2055 BinOpInit::get(BinOpInit::STRCONCAT,
2056 CurRec.getNameInit(),
2057 StringInit::get(Scoper),
2058 Type)->Fold(&CurRec, CurMultiClass),
2062 if (CurMultiClass && Scoper != "::") {
2064 BinOpInit::get(BinOpInit::STRCONCAT,
2065 BinOpInit::get(BinOpInit::STRCONCAT,
2066 CurMultiClass->Rec.getNameInit(),
2067 StringInit::get("::"),
2068 Type)->Fold(&CurRec, CurMultiClass),
2069 NewName->Fold(&CurRec, CurMultiClass),
2073 return NewName->Fold(&CurRec, CurMultiClass);
2076 /// QualifyName - Return an Init with a qualifier prefix referring
2077 /// to CurRec's name.
2078 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2079 const std::string &Name,
2080 const std::string &Scoper) {
2081 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);