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 DagRecTy DagRecTy::Shared;
83 void RecTy::anchor() { }
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 *DagRecTy::convertValue(TypedInit *TI) {
319 if (TI->getType()->typeIsConvertibleTo(this))
324 Init *DagRecTy::convertValue(UnOpInit *BO) {
325 if (BO->getOpcode() == UnOpInit::CAST) {
326 Init *L = BO->getOperand()->convertInitializerTo(this);
327 if (L == 0) return 0;
328 if (L != BO->getOperand())
329 return UnOpInit::get(UnOpInit::CAST, L, new DagRecTy);
335 Init *DagRecTy::convertValue(BinOpInit *BO) {
336 if (BO->getOpcode() == BinOpInit::CONCAT) {
337 Init *L = BO->getLHS()->convertInitializerTo(this);
338 Init *R = BO->getRHS()->convertInitializerTo(this);
339 if (L == 0 || R == 0) return 0;
340 if (L != BO->getLHS() || R != BO->getRHS())
341 return BinOpInit::get(BinOpInit::CONCAT, L, R, new DagRecTy);
347 RecordRecTy *RecordRecTy::get(Record *R) {
348 return &dynamic_cast<RecordRecTy&>(*R->getDefInit()->getType());
351 std::string RecordRecTy::getAsString() const {
352 return Rec->getName();
355 Init *RecordRecTy::convertValue(DefInit *DI) {
356 // Ensure that DI is a subclass of Rec.
357 if (!DI->getDef()->isSubClassOf(Rec))
362 Init *RecordRecTy::convertValue(TypedInit *TI) {
363 // Ensure that TI is compatible with Rec.
364 if (RecordRecTy *RRT = dynamic_cast<RecordRecTy*>(TI->getType()))
365 if (RRT->getRecord()->isSubClassOf(getRecord()) ||
366 RRT->getRecord() == getRecord())
371 bool RecordRecTy::baseClassOf(const RecordRecTy *RHS) const {
372 if (Rec == RHS->getRecord() || RHS->getRecord()->isSubClassOf(Rec))
375 const std::vector<Record*> &SC = Rec->getSuperClasses();
376 for (unsigned i = 0, e = SC.size(); i != e; ++i)
377 if (RHS->getRecord()->isSubClassOf(SC[i]))
384 /// resolveTypes - Find a common type that T1 and T2 convert to.
385 /// Return 0 if no such type exists.
387 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
388 if (!T1->typeIsConvertibleTo(T2)) {
389 if (!T2->typeIsConvertibleTo(T1)) {
390 // If one is a Record type, check superclasses
391 RecordRecTy *RecTy1 = dynamic_cast<RecordRecTy*>(T1);
393 // See if T2 inherits from a type T1 also inherits from
394 const std::vector<Record *> &T1SuperClasses =
395 RecTy1->getRecord()->getSuperClasses();
396 for(std::vector<Record *>::const_iterator i = T1SuperClasses.begin(),
397 iend = T1SuperClasses.end();
400 RecordRecTy *SuperRecTy1 = RecordRecTy::get(*i);
401 RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
403 if (NewType1 != SuperRecTy1) {
410 RecordRecTy *RecTy2 = dynamic_cast<RecordRecTy*>(T2);
412 // See if T1 inherits from a type T2 also inherits from
413 const std::vector<Record *> &T2SuperClasses =
414 RecTy2->getRecord()->getSuperClasses();
415 for (std::vector<Record *>::const_iterator i = T2SuperClasses.begin(),
416 iend = T2SuperClasses.end();
419 RecordRecTy *SuperRecTy2 = RecordRecTy::get(*i);
420 RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
422 if (NewType2 != SuperRecTy2) {
437 //===----------------------------------------------------------------------===//
438 // Initializer implementations
439 //===----------------------------------------------------------------------===//
441 void Init::anchor() { }
442 void Init::dump() const { return print(errs()); }
444 void UnsetInit::anchor() { }
446 UnsetInit *UnsetInit::get() {
447 static UnsetInit TheInit;
451 void BitInit::anchor() { }
453 BitInit *BitInit::get(bool V) {
454 static BitInit True(true);
455 static BitInit False(false);
457 return V ? &True : &False;
461 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
462 ID.AddInteger(Range.size());
464 for (ArrayRef<Init *>::iterator i = Range.begin(),
471 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
472 typedef FoldingSet<BitsInit> Pool;
476 ProfileBitsInit(ID, Range);
479 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
482 BitsInit *I = new BitsInit(Range);
483 ThePool.InsertNode(I, IP);
488 void BitsInit::Profile(FoldingSetNodeID &ID) const {
489 ProfileBitsInit(ID, Bits);
493 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
494 SmallVector<Init *, 16> NewBits(Bits.size());
496 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
497 if (Bits[i] >= getNumBits())
499 NewBits[i] = getBit(Bits[i]);
501 return BitsInit::get(NewBits);
504 std::string BitsInit::getAsString() const {
505 std::string Result = "{ ";
506 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
507 if (i) Result += ", ";
508 if (Init *Bit = getBit(e-i-1))
509 Result += Bit->getAsString();
513 return Result + " }";
516 // resolveReferences - If there are any field references that refer to fields
517 // that have been filled in, we can propagate the values now.
519 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
520 bool Changed = false;
521 SmallVector<Init *, 16> NewBits(getNumBits());
523 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
525 Init *CurBit = getBit(i);
529 CurBit = CurBit->resolveReferences(R, RV);
530 Changed |= B != CurBit;
531 } while (B != CurBit);
536 return BitsInit::get(NewBits);
538 return const_cast<BitsInit *>(this);
541 IntInit *IntInit::get(int64_t V) {
542 typedef DenseMap<int64_t, IntInit *> Pool;
545 IntInit *&I = ThePool[V];
546 if (!I) I = new IntInit(V);
550 std::string IntInit::getAsString() const {
551 return itostr(Value);
555 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
556 SmallVector<Init *, 16> NewBits(Bits.size());
558 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
562 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
564 return BitsInit::get(NewBits);
567 void StringInit::anchor() { }
569 StringInit *StringInit::get(StringRef V) {
570 typedef StringMap<StringInit *> Pool;
573 StringInit *&I = ThePool[V];
574 if (!I) I = new StringInit(V);
578 static void ProfileListInit(FoldingSetNodeID &ID,
579 ArrayRef<Init *> Range,
581 ID.AddInteger(Range.size());
582 ID.AddPointer(EltTy);
584 for (ArrayRef<Init *>::iterator i = Range.begin(),
591 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
592 typedef FoldingSet<ListInit> Pool;
595 // Just use the FoldingSetNodeID to compute a hash. Use a DenseMap
596 // for actual storage.
598 ProfileListInit(ID, Range, EltTy);
601 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
604 ListInit *I = new ListInit(Range, EltTy);
605 ThePool.InsertNode(I, IP);
609 void ListInit::Profile(FoldingSetNodeID &ID) const {
610 ListRecTy *ListType = dynamic_cast<ListRecTy *>(getType());
611 assert(ListType && "Bad type for ListInit!");
612 RecTy *EltTy = ListType->getElementType();
614 ProfileListInit(ID, Values, EltTy);
618 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
619 std::vector<Init*> Vals;
620 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
621 if (Elements[i] >= getSize())
623 Vals.push_back(getElement(Elements[i]));
625 return ListInit::get(Vals, getType());
628 Record *ListInit::getElementAsRecord(unsigned i) const {
629 assert(i < Values.size() && "List element index out of range!");
630 DefInit *DI = dynamic_cast<DefInit*>(Values[i]);
631 if (DI == 0) throw "Expected record in list!";
635 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
636 std::vector<Init*> Resolved;
637 Resolved.reserve(getSize());
638 bool Changed = false;
640 for (unsigned i = 0, e = getSize(); i != e; ++i) {
642 Init *CurElt = getElement(i);
646 CurElt = CurElt->resolveReferences(R, RV);
647 Changed |= E != CurElt;
648 } while (E != CurElt);
649 Resolved.push_back(E);
653 return ListInit::get(Resolved, getType());
654 return const_cast<ListInit *>(this);
657 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
658 unsigned Elt) const {
659 if (Elt >= getSize())
660 return 0; // Out of range reference.
661 Init *E = getElement(Elt);
662 // If the element is set to some value, or if we are resolving a reference
663 // to a specific variable and that variable is explicitly unset, then
664 // replace the VarListElementInit with it.
665 if (IRV || !dynamic_cast<UnsetInit*>(E))
670 std::string ListInit::getAsString() const {
671 std::string Result = "[";
672 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
673 if (i) Result += ", ";
674 Result += Values[i]->getAsString();
679 Init *OpInit::resolveBitReference(Record &R, const RecordVal *IRV,
680 unsigned Bit) const {
681 Init *Folded = Fold(&R, 0);
683 if (Folded != this) {
684 TypedInit *Typed = dynamic_cast<TypedInit *>(Folded);
686 return Typed->resolveBitReference(R, IRV, Bit);
693 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
694 unsigned Elt) const {
695 Init *Resolved = resolveReferences(R, IRV);
696 OpInit *OResolved = dynamic_cast<OpInit *>(Resolved);
698 Resolved = OResolved->Fold(&R, 0);
701 if (Resolved != this) {
702 TypedInit *Typed = dynamic_cast<TypedInit *>(Resolved);
703 assert(Typed && "Expected typed init for list reference");
705 Init *New = Typed->resolveListElementReference(R, IRV, Elt);
708 return VarListElementInit::get(Typed, Elt);
715 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
716 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
718 typedef DenseMap<Key, UnOpInit *> Pool;
721 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
723 UnOpInit *&I = ThePool[TheKey];
724 if (!I) I = new UnOpInit(opc, lhs, Type);
728 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
729 switch (getOpcode()) {
730 default: assert(0 && "Unknown unop");
732 if (getType()->getAsString() == "string") {
733 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
738 DefInit *LHSd = dynamic_cast<DefInit*>(LHS);
740 return StringInit::get(LHSd->getDef()->getName());
743 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
745 std::string Name = LHSs->getValue();
747 // From TGParser::ParseIDValue
749 if (const RecordVal *RV = CurRec->getValue(Name)) {
750 if (RV->getType() != getType())
751 throw "type mismatch in cast";
752 return VarInit::get(Name, RV->getType());
755 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
758 if (CurRec->isTemplateArg(TemplateArgName)) {
759 const RecordVal *RV = CurRec->getValue(TemplateArgName);
760 assert(RV && "Template arg doesn't exist??");
762 if (RV->getType() != getType())
763 throw "type mismatch in cast";
765 return VarInit::get(TemplateArgName, RV->getType());
770 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
772 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
773 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
774 assert(RV && "Template arg doesn't exist??");
776 if (RV->getType() != getType())
777 throw "type mismatch in cast";
779 return VarInit::get(MCName, RV->getType());
783 if (Record *D = (CurRec->getRecords()).getDef(Name))
784 return DefInit::get(D);
786 throw TGError(CurRec->getLoc(), "Undefined reference:'" + Name + "'\n");
792 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
794 if (LHSl->getSize() == 0) {
795 assert(0 && "Empty list in car");
798 return LHSl->getElement(0);
803 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
805 if (LHSl->getSize() == 0) {
806 assert(0 && "Empty list in cdr");
809 // Note the +1. We can't just pass the result of getValues()
811 ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
812 ArrayRef<Init *>::iterator end = LHSl->getValues().end();
814 ListInit::get(ArrayRef<Init *>(begin, end - begin),
821 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
823 if (LHSl->getSize() == 0) {
824 return IntInit::get(1);
826 return IntInit::get(0);
829 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
831 if (LHSs->getValue().empty()) {
832 return IntInit::get(1);
834 return IntInit::get(0);
841 return const_cast<UnOpInit *>(this);
844 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
845 Init *lhs = LHS->resolveReferences(R, RV);
848 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, 0);
852 std::string UnOpInit::getAsString() const {
855 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
856 case HEAD: Result = "!head"; break;
857 case TAIL: Result = "!tail"; break;
858 case EMPTY: Result = "!empty"; break;
860 return Result + "(" + LHS->getAsString() + ")";
863 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
864 Init *rhs, RecTy *Type) {
866 std::pair<std::pair<unsigned, Init *>, Init *>,
870 typedef DenseMap<Key, BinOpInit *> Pool;
873 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
876 BinOpInit *&I = ThePool[TheKey];
877 if (!I) I = new BinOpInit(opc, lhs, rhs, Type);
881 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
882 switch (getOpcode()) {
883 default: assert(0 && "Unknown binop");
885 DagInit *LHSs = dynamic_cast<DagInit*>(LHS);
886 DagInit *RHSs = dynamic_cast<DagInit*>(RHS);
888 DefInit *LOp = dynamic_cast<DefInit*>(LHSs->getOperator());
889 DefInit *ROp = dynamic_cast<DefInit*>(RHSs->getOperator());
890 if (LOp == 0 || ROp == 0 || LOp->getDef() != ROp->getDef())
891 throw "Concated Dag operators do not match!";
892 std::vector<Init*> Args;
893 std::vector<std::string> ArgNames;
894 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
895 Args.push_back(LHSs->getArg(i));
896 ArgNames.push_back(LHSs->getArgName(i));
898 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
899 Args.push_back(RHSs->getArg(i));
900 ArgNames.push_back(RHSs->getArgName(i));
902 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
907 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
908 StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
910 return StringInit::get(LHSs->getValue() + RHSs->getValue());
914 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
915 // to string objects.
917 dynamic_cast<IntInit*>(LHS->convertInitializerTo(IntRecTy::get()));
919 dynamic_cast<IntInit*>(RHS->convertInitializerTo(IntRecTy::get()));
922 return IntInit::get(L->getValue() == R->getValue());
924 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
925 StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
927 // Make sure we've resolved
929 return IntInit::get(LHSs->getValue() == RHSs->getValue());
936 IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
937 IntInit *RHSi = dynamic_cast<IntInit*>(RHS);
939 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
941 switch (getOpcode()) {
942 default: assert(0 && "Bad opcode!");
943 case SHL: Result = LHSv << RHSv; break;
944 case SRA: Result = LHSv >> RHSv; break;
945 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
947 return IntInit::get(Result);
952 return const_cast<BinOpInit *>(this);
955 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
956 Init *lhs = LHS->resolveReferences(R, RV);
957 Init *rhs = RHS->resolveReferences(R, RV);
959 if (LHS != lhs || RHS != rhs)
960 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R, 0);
964 std::string BinOpInit::getAsString() const {
967 case CONCAT: Result = "!con"; break;
968 case SHL: Result = "!shl"; break;
969 case SRA: Result = "!sra"; break;
970 case SRL: Result = "!srl"; break;
971 case EQ: Result = "!eq"; break;
972 case STRCONCAT: Result = "!strconcat"; break;
974 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
977 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs,
978 Init *mhs, Init *rhs,
982 std::pair<std::pair<unsigned, RecTy *>, Init *>,
988 typedef DenseMap<Key, TernOpInit *> Pool;
991 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
997 TernOpInit *&I = ThePool[TheKey];
998 if (!I) I = new TernOpInit(opc, lhs, mhs, rhs, Type);
1002 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1003 Record *CurRec, MultiClass *CurMultiClass);
1005 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
1006 RecTy *Type, Record *CurRec,
1007 MultiClass *CurMultiClass) {
1008 std::vector<Init *> NewOperands;
1010 TypedInit *TArg = dynamic_cast<TypedInit*>(Arg);
1012 // If this is a dag, recurse
1013 if (TArg && TArg->getType()->getAsString() == "dag") {
1014 Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
1015 CurRec, CurMultiClass);
1023 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
1024 OpInit *RHSoo = dynamic_cast<OpInit*>(RHSo->getOperand(i));
1027 Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1028 Type, CurRec, CurMultiClass);
1030 NewOperands.push_back(Result);
1032 NewOperands.push_back(Arg);
1034 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1035 NewOperands.push_back(Arg);
1037 NewOperands.push_back(RHSo->getOperand(i));
1041 // Now run the operator and use its result as the new leaf
1042 const OpInit *NewOp = RHSo->clone(NewOperands);
1043 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
1044 if (NewVal != NewOp)
1050 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1051 Record *CurRec, MultiClass *CurMultiClass) {
1052 DagInit *MHSd = dynamic_cast<DagInit*>(MHS);
1053 ListInit *MHSl = dynamic_cast<ListInit*>(MHS);
1055 DagRecTy *DagType = dynamic_cast<DagRecTy*>(Type);
1056 ListRecTy *ListType = dynamic_cast<ListRecTy*>(Type);
1058 OpInit *RHSo = dynamic_cast<OpInit*>(RHS);
1061 throw TGError(CurRec->getLoc(), "!foreach requires an operator\n");
1064 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
1067 throw TGError(CurRec->getLoc(), "!foreach requires typed variable\n");
1070 if ((MHSd && DagType) || (MHSl && ListType)) {
1072 Init *Val = MHSd->getOperator();
1073 Init *Result = EvaluateOperation(RHSo, LHS, Val,
1074 Type, CurRec, CurMultiClass);
1079 std::vector<std::pair<Init *, std::string> > args;
1080 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1082 std::string ArgName;
1083 Arg = MHSd->getArg(i);
1084 ArgName = MHSd->getArgName(i);
1087 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1088 CurRec, CurMultiClass);
1093 // TODO: Process arg names
1094 args.push_back(std::make_pair(Arg, ArgName));
1097 return DagInit::get(Val, "", args);
1100 std::vector<Init *> NewOperands;
1101 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1103 for (std::vector<Init *>::iterator li = NewList.begin(),
1104 liend = NewList.end();
1108 NewOperands.clear();
1109 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1110 // First, replace the foreach variable with the list item
1111 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1112 NewOperands.push_back(Item);
1114 NewOperands.push_back(RHSo->getOperand(i));
1118 // Now run the operator and use its result as the new list item
1119 const OpInit *NewOp = RHSo->clone(NewOperands);
1120 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1121 if (NewItem != NewOp)
1124 return ListInit::get(NewList, MHSl->getType());
1130 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1131 switch (getOpcode()) {
1132 default: assert(0 && "Unknown binop");
1134 DefInit *LHSd = dynamic_cast<DefInit*>(LHS);
1135 VarInit *LHSv = dynamic_cast<VarInit*>(LHS);
1136 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
1138 DefInit *MHSd = dynamic_cast<DefInit*>(MHS);
1139 VarInit *MHSv = dynamic_cast<VarInit*>(MHS);
1140 StringInit *MHSs = dynamic_cast<StringInit*>(MHS);
1142 DefInit *RHSd = dynamic_cast<DefInit*>(RHS);
1143 VarInit *RHSv = dynamic_cast<VarInit*>(RHS);
1144 StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
1146 if ((LHSd && MHSd && RHSd)
1147 || (LHSv && MHSv && RHSv)
1148 || (LHSs && MHSs && RHSs)) {
1150 Record *Val = RHSd->getDef();
1151 if (LHSd->getAsString() == RHSd->getAsString()) {
1152 Val = MHSd->getDef();
1154 return DefInit::get(Val);
1157 std::string Val = RHSv->getName();
1158 if (LHSv->getAsString() == RHSv->getAsString()) {
1159 Val = MHSv->getName();
1161 return VarInit::get(Val, getType());
1164 std::string Val = RHSs->getValue();
1166 std::string::size_type found;
1167 std::string::size_type idx = 0;
1169 found = Val.find(LHSs->getValue(), idx);
1170 if (found != std::string::npos) {
1171 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1173 idx = found + MHSs->getValue().size();
1174 } while (found != std::string::npos);
1176 return StringInit::get(Val);
1183 Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1184 CurRec, CurMultiClass);
1192 IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
1193 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1194 LHSi = dynamic_cast<IntInit*>(I);
1196 if (LHSi->getValue()) {
1206 return const_cast<TernOpInit *>(this);
1209 Init *TernOpInit::resolveReferences(Record &R,
1210 const RecordVal *RV) const {
1211 Init *lhs = LHS->resolveReferences(R, RV);
1213 if (Opc == IF && lhs != LHS) {
1214 IntInit *Value = dynamic_cast<IntInit*>(lhs);
1215 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1216 Value = dynamic_cast<IntInit*>(I);
1219 if (Value->getValue()) {
1220 Init *mhs = MHS->resolveReferences(R, RV);
1221 return (TernOpInit::get(getOpcode(), lhs, mhs,
1222 RHS, getType()))->Fold(&R, 0);
1224 Init *rhs = RHS->resolveReferences(R, RV);
1225 return (TernOpInit::get(getOpcode(), lhs, MHS,
1226 rhs, getType()))->Fold(&R, 0);
1231 Init *mhs = MHS->resolveReferences(R, RV);
1232 Init *rhs = RHS->resolveReferences(R, RV);
1234 if (LHS != lhs || MHS != mhs || RHS != rhs)
1235 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1236 getType()))->Fold(&R, 0);
1240 std::string TernOpInit::getAsString() const {
1243 case SUBST: Result = "!subst"; break;
1244 case FOREACH: Result = "!foreach"; break;
1245 case IF: Result = "!if"; break;
1247 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
1248 + RHS->getAsString() + ")";
1251 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1252 RecordRecTy *RecordType = dynamic_cast<RecordRecTy *>(getType());
1254 RecordVal *Field = RecordType->getRecord()->getValue(FieldName);
1256 return Field->getType();
1263 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1264 BitsRecTy *T = dynamic_cast<BitsRecTy*>(getType());
1265 if (T == 0) return 0; // Cannot subscript a non-bits variable.
1266 unsigned NumBits = T->getNumBits();
1268 SmallVector<Init *, 16> NewBits(Bits.size());
1269 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1270 if (Bits[i] >= NumBits)
1273 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1275 return BitsInit::get(NewBits);
1279 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1280 ListRecTy *T = dynamic_cast<ListRecTy*>(getType());
1281 if (T == 0) return 0; // Cannot subscript a non-list variable.
1283 if (Elements.size() == 1)
1284 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1286 std::vector<Init*> ListInits;
1287 ListInits.reserve(Elements.size());
1288 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1289 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1291 return ListInit::get(ListInits, T);
1295 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1296 Init *Value = StringInit::get(VN);
1297 return VarInit::get(Value, T);
1300 VarInit *VarInit::get(Init *VN, RecTy *T) {
1301 typedef std::pair<RecTy *, Init *> Key;
1302 typedef DenseMap<Key, VarInit *> Pool;
1303 static Pool ThePool;
1305 Key TheKey(std::make_pair(T, VN));
1307 VarInit *&I = ThePool[TheKey];
1308 if (!I) I = new VarInit(VN, T);
1312 const std::string &VarInit::getName() const {
1313 StringInit *NameString =
1314 dynamic_cast<StringInit *>(getNameInit());
1315 assert(NameString && "VarInit name is not a string!");
1316 return NameString->getValue();
1319 Init *VarInit::resolveBitReference(Record &R, const RecordVal *IRV,
1320 unsigned Bit) const {
1321 if (R.isTemplateArg(getNameInit())) return 0;
1322 if (IRV && IRV->getNameInit() != getNameInit()) return 0;
1324 RecordVal *RV = R.getValue(getNameInit());
1325 assert(RV && "Reference to a non-existent variable?");
1326 assert(dynamic_cast<BitsInit*>(RV->getValue()));
1327 BitsInit *BI = (BitsInit*)RV->getValue();
1329 assert(Bit < BI->getNumBits() && "Bit reference out of range!");
1330 Init *B = BI->getBit(Bit);
1332 // If the bit is set to some value, or if we are resolving a reference to a
1333 // specific variable and that variable is explicitly unset, then replace the
1334 // VarBitInit with it.
1335 if (IRV || !dynamic_cast<UnsetInit*>(B))
1340 Init *VarInit::resolveListElementReference(Record &R,
1341 const RecordVal *IRV,
1342 unsigned Elt) const {
1343 if (R.isTemplateArg(getNameInit())) return 0;
1344 if (IRV && IRV->getNameInit() != getNameInit()) return 0;
1346 RecordVal *RV = R.getValue(getNameInit());
1347 assert(RV && "Reference to a non-existent variable?");
1348 ListInit *LI = dynamic_cast<ListInit*>(RV->getValue());
1350 TypedInit *VI = dynamic_cast<TypedInit*>(RV->getValue());
1351 assert(VI && "Invalid list element!");
1352 return VarListElementInit::get(VI, Elt);
1355 if (Elt >= LI->getSize())
1356 return 0; // Out of range reference.
1357 Init *E = LI->getElement(Elt);
1358 // If the element is set to some value, or if we are resolving a reference
1359 // to a specific variable and that variable is explicitly unset, then
1360 // replace the VarListElementInit with it.
1361 if (IRV || !dynamic_cast<UnsetInit*>(E))
1367 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1368 if (RecordRecTy *RTy = dynamic_cast<RecordRecTy*>(getType()))
1369 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1370 return RV->getType();
1374 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1375 const std::string &FieldName) const {
1376 if (dynamic_cast<RecordRecTy*>(getType()))
1377 if (const RecordVal *Val = R.getValue(VarName)) {
1378 if (RV != Val && (RV || dynamic_cast<UnsetInit*>(Val->getValue())))
1380 Init *TheInit = Val->getValue();
1381 assert(TheInit != this && "Infinite loop detected!");
1382 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1390 /// resolveReferences - This method is used by classes that refer to other
1391 /// variables which may not be defined at the time the expression is formed.
1392 /// If a value is set for the variable later, this method will be called on
1393 /// users of the value to allow the value to propagate out.
1395 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1396 if (RecordVal *Val = R.getValue(VarName))
1397 if (RV == Val || (RV == 0 && !dynamic_cast<UnsetInit*>(Val->getValue())))
1398 return Val->getValue();
1399 return const_cast<VarInit *>(this);
1402 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1403 typedef std::pair<TypedInit *, unsigned> Key;
1404 typedef DenseMap<Key, VarBitInit *> Pool;
1406 static Pool ThePool;
1408 Key TheKey(std::make_pair(T, B));
1410 VarBitInit *&I = ThePool[TheKey];
1411 if (!I) I = new VarBitInit(T, B);
1415 std::string VarBitInit::getAsString() const {
1416 return TI->getAsString() + "{" + utostr(Bit) + "}";
1419 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1420 if (Init *I = getVariable()->resolveBitReference(R, RV, getBitNum()))
1422 return const_cast<VarBitInit *>(this);
1425 VarListElementInit *VarListElementInit::get(TypedInit *T,
1427 typedef std::pair<TypedInit *, unsigned> Key;
1428 typedef DenseMap<Key, VarListElementInit *> Pool;
1430 static Pool ThePool;
1432 Key TheKey(std::make_pair(T, E));
1434 VarListElementInit *&I = ThePool[TheKey];
1435 if (!I) I = new VarListElementInit(T, E);
1439 std::string VarListElementInit::getAsString() const {
1440 return TI->getAsString() + "[" + utostr(Element) + "]";
1444 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1445 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1448 return const_cast<VarListElementInit *>(this);
1451 Init *VarListElementInit::resolveBitReference(Record &R, const RecordVal *RV,
1452 unsigned Bit) const {
1453 // FIXME: This should be implemented, to support references like:
1454 // bit B = AA[0]{1};
1458 Init *VarListElementInit:: resolveListElementReference(Record &R,
1459 const RecordVal *RV,
1460 unsigned Elt) const {
1461 Init *Result = TI->resolveListElementReference(R, RV, Element);
1464 TypedInit *TInit = dynamic_cast<TypedInit *>(Result);
1466 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1467 if (Result2) return Result2;
1468 return new VarListElementInit(TInit, Elt);
1476 DefInit *DefInit::get(Record *R) {
1477 return R->getDefInit();
1480 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1481 if (const RecordVal *RV = Def->getValue(FieldName))
1482 return RV->getType();
1486 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1487 const std::string &FieldName) const {
1488 return Def->getValue(FieldName)->getValue();
1492 std::string DefInit::getAsString() const {
1493 return Def->getName();
1496 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1497 typedef std::pair<Init *, TableGenStringKey> Key;
1498 typedef DenseMap<Key, FieldInit *> Pool;
1499 static Pool ThePool;
1501 Key TheKey(std::make_pair(R, FN));
1503 FieldInit *&I = ThePool[TheKey];
1504 if (!I) I = new FieldInit(R, FN);
1508 Init *FieldInit::resolveBitReference(Record &R, const RecordVal *RV,
1509 unsigned Bit) const {
1510 if (Init *BitsVal = Rec->getFieldInit(R, RV, FieldName))
1511 if (BitsInit *BI = dynamic_cast<BitsInit*>(BitsVal)) {
1512 assert(Bit < BI->getNumBits() && "Bit reference out of range!");
1513 Init *B = BI->getBit(Bit);
1515 if (dynamic_cast<BitInit*>(B)) // If the bit is set.
1516 return B; // Replace the VarBitInit with it.
1521 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1522 unsigned Elt) const {
1523 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1524 if (ListInit *LI = dynamic_cast<ListInit*>(ListVal)) {
1525 if (Elt >= LI->getSize()) return 0;
1526 Init *E = LI->getElement(Elt);
1528 // If the element is set to some value, or if we are resolving a
1529 // reference to a specific variable and that variable is explicitly
1530 // unset, then replace the VarListElementInit with it.
1531 if (RV || !dynamic_cast<UnsetInit*>(E))
1537 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1538 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1540 Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1542 Init *BVR = BitsVal->resolveReferences(R, RV);
1543 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1546 if (NewRec != Rec) {
1547 return FieldInit::get(NewRec, FieldName);
1549 return const_cast<FieldInit *>(this);
1552 void ProfileDagInit(FoldingSetNodeID &ID,
1554 const std::string &VN,
1555 ArrayRef<Init *> ArgRange,
1556 ArrayRef<std::string> NameRange) {
1560 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1561 ArrayRef<std::string>::iterator Name = NameRange.begin();
1562 while (Arg != ArgRange.end()) {
1563 assert(Name != NameRange.end() && "Arg name underflow!");
1564 ID.AddPointer(*Arg++);
1565 ID.AddString(*Name++);
1567 assert(Name == NameRange.end() && "Arg name overflow!");
1571 DagInit::get(Init *V, const std::string &VN,
1572 ArrayRef<Init *> ArgRange,
1573 ArrayRef<std::string> NameRange) {
1574 typedef FoldingSet<DagInit> Pool;
1575 static Pool ThePool;
1577 FoldingSetNodeID ID;
1578 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1581 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1584 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1585 ThePool.InsertNode(I, IP);
1591 DagInit::get(Init *V, const std::string &VN,
1592 const std::vector<std::pair<Init*, std::string> > &args) {
1593 typedef std::pair<Init*, std::string> PairType;
1595 std::vector<Init *> Args;
1596 std::vector<std::string> Names;
1598 for (std::vector<PairType>::const_iterator i = args.begin(),
1602 Args.push_back(i->first);
1603 Names.push_back(i->second);
1606 return DagInit::get(V, VN, Args, Names);
1609 void DagInit::Profile(FoldingSetNodeID &ID) const {
1610 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1613 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1614 std::vector<Init*> NewArgs;
1615 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1616 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1618 Init *Op = Val->resolveReferences(R, RV);
1620 if (Args != NewArgs || Op != Val)
1621 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1623 return const_cast<DagInit *>(this);
1627 std::string DagInit::getAsString() const {
1628 std::string Result = "(" + Val->getAsString();
1629 if (!ValName.empty())
1630 Result += ":" + ValName;
1632 Result += " " + Args[0]->getAsString();
1633 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1634 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1635 Result += ", " + Args[i]->getAsString();
1636 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1639 return Result + ")";
1643 //===----------------------------------------------------------------------===//
1644 // Other implementations
1645 //===----------------------------------------------------------------------===//
1647 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1648 : Name(N), Ty(T), Prefix(P) {
1649 Value = Ty->convertValue(UnsetInit::get());
1650 assert(Value && "Cannot create unset value for current type!");
1653 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1654 : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1655 Value = Ty->convertValue(UnsetInit::get());
1656 assert(Value && "Cannot create unset value for current type!");
1659 const std::string &RecordVal::getName() const {
1660 StringInit *NameString = dynamic_cast<StringInit *>(Name);
1661 assert(NameString && "RecordVal name is not a string!");
1662 return NameString->getValue();
1665 void RecordVal::dump() const { errs() << *this; }
1667 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1668 if (getPrefix()) OS << "field ";
1669 OS << *getType() << " " << getNameInitAsString();
1672 OS << " = " << *getValue();
1674 if (PrintSem) OS << ";\n";
1677 unsigned Record::LastID = 0;
1679 void Record::init() {
1682 // Every record potentially has a def at the top. This value is
1683 // replaced with the top-level def name at instantiation time.
1684 RecordVal DN("NAME", StringRecTy::get(), 0);
1688 void Record::checkName() {
1689 // Ensure the record name has string type.
1690 const TypedInit *TypedName = dynamic_cast<const TypedInit *>(Name);
1691 assert(TypedName && "Record name is not typed!");
1692 RecTy *Type = TypedName->getType();
1693 if (dynamic_cast<StringRecTy *>(Type) == 0) {
1694 throw "Record name is not a string!";
1698 DefInit *Record::getDefInit() {
1700 TheInit = new DefInit(this, new RecordRecTy(this));
1704 const std::string &Record::getName() const {
1705 const StringInit *NameString =
1706 dynamic_cast<const StringInit *>(Name);
1707 assert(NameString && "Record name is not a string!");
1708 return NameString->getValue();
1711 void Record::setName(Init *NewName) {
1712 if (TrackedRecords.getDef(Name->getAsUnquotedString()) == this) {
1713 TrackedRecords.removeDef(Name->getAsUnquotedString());
1714 TrackedRecords.addDef(this);
1715 } else if (TrackedRecords.getClass(Name->getAsUnquotedString()) == this) {
1716 TrackedRecords.removeClass(Name->getAsUnquotedString());
1717 TrackedRecords.addClass(this);
1718 } // Otherwise this isn't yet registered.
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 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1745 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1747 void Record::resolveReferencesTo(const RecordVal *RV) {
1748 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1749 if (Init *V = Values[i].getValue())
1750 Values[i].setValue(V->resolveReferences(*this, RV));
1752 Init *OldName = getNameInit();
1753 Init *NewName = Name->resolveReferences(*this, RV);
1754 if (NewName != OldName) {
1755 // Re-register with RecordKeeper.
1760 void Record::dump() const { errs() << *this; }
1762 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1763 OS << R.getNameInitAsString();
1765 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1766 if (!TArgs.empty()) {
1768 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1770 const RecordVal *RV = R.getValue(TArgs[i]);
1771 assert(RV && "Template argument record not found??");
1772 RV->print(OS, false);
1778 const std::vector<Record*> &SC = R.getSuperClasses();
1781 for (unsigned i = 0, e = SC.size(); i != e; ++i)
1782 OS << " " << SC[i]->getNameInitAsString();
1786 const std::vector<RecordVal> &Vals = R.getValues();
1787 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1788 if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1790 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1791 if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1797 /// getValueInit - Return the initializer for a value with the specified name,
1798 /// or throw an exception if the field does not exist.
1800 Init *Record::getValueInit(StringRef FieldName) const {
1801 const RecordVal *R = getValue(FieldName);
1802 if (R == 0 || R->getValue() == 0)
1803 throw "Record `" + getName() + "' does not have a field named `" +
1804 FieldName.str() + "'!\n";
1805 return R->getValue();
1809 /// getValueAsString - This method looks up the specified field and returns its
1810 /// value as a string, throwing an exception if the field does not exist or if
1811 /// the value is not a string.
1813 std::string Record::getValueAsString(StringRef FieldName) const {
1814 const RecordVal *R = getValue(FieldName);
1815 if (R == 0 || R->getValue() == 0)
1816 throw "Record `" + getName() + "' does not have a field named `" +
1817 FieldName.str() + "'!\n";
1819 if (StringInit *SI = dynamic_cast<StringInit*>(R->getValue()))
1820 return SI->getValue();
1821 throw "Record `" + getName() + "', field `" + FieldName.str() +
1822 "' does not have a string initializer!";
1825 /// getValueAsBitsInit - This method looks up the specified field and returns
1826 /// its value as a BitsInit, throwing an exception if the field does not exist
1827 /// or if the value is not the right type.
1829 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1830 const RecordVal *R = getValue(FieldName);
1831 if (R == 0 || R->getValue() == 0)
1832 throw "Record `" + getName() + "' does not have a field named `" +
1833 FieldName.str() + "'!\n";
1835 if (BitsInit *BI = dynamic_cast<BitsInit*>(R->getValue()))
1837 throw "Record `" + getName() + "', field `" + FieldName.str() +
1838 "' does not have a BitsInit initializer!";
1841 /// getValueAsListInit - This method looks up the specified field and returns
1842 /// its value as a ListInit, throwing an exception if the field does not exist
1843 /// or if the value is not the right type.
1845 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1846 const RecordVal *R = getValue(FieldName);
1847 if (R == 0 || R->getValue() == 0)
1848 throw "Record `" + getName() + "' does not have a field named `" +
1849 FieldName.str() + "'!\n";
1851 if (ListInit *LI = dynamic_cast<ListInit*>(R->getValue()))
1853 throw "Record `" + getName() + "', field `" + FieldName.str() +
1854 "' does not have a list initializer!";
1857 /// getValueAsListOfDefs - This method looks up the specified field and returns
1858 /// its value as a vector of records, throwing an exception if the field does
1859 /// not exist or if the value is not the right type.
1861 std::vector<Record*>
1862 Record::getValueAsListOfDefs(StringRef FieldName) const {
1863 ListInit *List = getValueAsListInit(FieldName);
1864 std::vector<Record*> Defs;
1865 for (unsigned i = 0; i < List->getSize(); i++) {
1866 if (DefInit *DI = dynamic_cast<DefInit*>(List->getElement(i))) {
1867 Defs.push_back(DI->getDef());
1869 throw "Record `" + getName() + "', field `" + FieldName.str() +
1870 "' list is not entirely DefInit!";
1876 /// getValueAsInt - This method looks up the specified field and returns its
1877 /// value as an int64_t, throwing an exception if the field does not exist or if
1878 /// the value is not the right type.
1880 int64_t Record::getValueAsInt(StringRef FieldName) const {
1881 const RecordVal *R = getValue(FieldName);
1882 if (R == 0 || R->getValue() == 0)
1883 throw "Record `" + getName() + "' does not have a field named `" +
1884 FieldName.str() + "'!\n";
1886 if (IntInit *II = dynamic_cast<IntInit*>(R->getValue()))
1887 return II->getValue();
1888 throw "Record `" + getName() + "', field `" + FieldName.str() +
1889 "' does not have an int initializer!";
1892 /// getValueAsListOfInts - This method looks up the specified field and returns
1893 /// its value as a vector of integers, throwing an exception if the field does
1894 /// not exist or if the value is not the right type.
1896 std::vector<int64_t>
1897 Record::getValueAsListOfInts(StringRef FieldName) const {
1898 ListInit *List = getValueAsListInit(FieldName);
1899 std::vector<int64_t> Ints;
1900 for (unsigned i = 0; i < List->getSize(); i++) {
1901 if (IntInit *II = dynamic_cast<IntInit*>(List->getElement(i))) {
1902 Ints.push_back(II->getValue());
1904 throw "Record `" + getName() + "', field `" + FieldName.str() +
1905 "' does not have a list of ints initializer!";
1911 /// getValueAsListOfStrings - This method looks up the specified field and
1912 /// returns its value as a vector of strings, throwing an exception if the
1913 /// field does not exist or if the value is not the right type.
1915 std::vector<std::string>
1916 Record::getValueAsListOfStrings(StringRef FieldName) const {
1917 ListInit *List = getValueAsListInit(FieldName);
1918 std::vector<std::string> Strings;
1919 for (unsigned i = 0; i < List->getSize(); i++) {
1920 if (StringInit *II = dynamic_cast<StringInit*>(List->getElement(i))) {
1921 Strings.push_back(II->getValue());
1923 throw "Record `" + getName() + "', field `" + FieldName.str() +
1924 "' does not have a list of strings initializer!";
1930 /// getValueAsDef - This method looks up the specified field and returns its
1931 /// value as a Record, throwing an exception if the field does not exist or if
1932 /// the value is not the right type.
1934 Record *Record::getValueAsDef(StringRef FieldName) const {
1935 const RecordVal *R = getValue(FieldName);
1936 if (R == 0 || R->getValue() == 0)
1937 throw "Record `" + getName() + "' does not have a field named `" +
1938 FieldName.str() + "'!\n";
1940 if (DefInit *DI = dynamic_cast<DefInit*>(R->getValue()))
1941 return DI->getDef();
1942 throw "Record `" + getName() + "', field `" + FieldName.str() +
1943 "' does not have a def initializer!";
1946 /// getValueAsBit - This method looks up the specified field and returns its
1947 /// value as a bit, throwing an exception if the field does not exist or if
1948 /// the value is not the right type.
1950 bool Record::getValueAsBit(StringRef FieldName) const {
1951 const RecordVal *R = getValue(FieldName);
1952 if (R == 0 || R->getValue() == 0)
1953 throw "Record `" + getName() + "' does not have a field named `" +
1954 FieldName.str() + "'!\n";
1956 if (BitInit *BI = dynamic_cast<BitInit*>(R->getValue()))
1957 return BI->getValue();
1958 throw "Record `" + getName() + "', field `" + FieldName.str() +
1959 "' does not have a bit initializer!";
1962 /// getValueAsDag - This method looks up the specified field and returns its
1963 /// value as an Dag, throwing an exception if the field does not exist or if
1964 /// the value is not the right type.
1966 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1967 const RecordVal *R = getValue(FieldName);
1968 if (R == 0 || R->getValue() == 0)
1969 throw "Record `" + getName() + "' does not have a field named `" +
1970 FieldName.str() + "'!\n";
1972 if (DagInit *DI = dynamic_cast<DagInit*>(R->getValue()))
1974 throw "Record `" + getName() + "', field `" + FieldName.str() +
1975 "' does not have a dag initializer!";
1979 void MultiClass::dump() const {
1980 errs() << "Record:\n";
1983 errs() << "Defs:\n";
1984 for (RecordVector::const_iterator r = DefPrototypes.begin(),
1985 rend = DefPrototypes.end();
1993 void RecordKeeper::dump() const { errs() << *this; }
1995 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1996 OS << "------------- Classes -----------------\n";
1997 const std::map<std::string, Record*> &Classes = RK.getClasses();
1998 for (std::map<std::string, Record*>::const_iterator I = Classes.begin(),
1999 E = Classes.end(); I != E; ++I)
2000 OS << "class " << *I->second;
2002 OS << "------------- Defs -----------------\n";
2003 const std::map<std::string, Record*> &Defs = RK.getDefs();
2004 for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),
2005 E = Defs.end(); I != E; ++I)
2006 OS << "def " << *I->second;
2011 /// getAllDerivedDefinitions - This method returns all concrete definitions
2012 /// that derive from the specified class name. If a class with the specified
2013 /// name does not exist, an error is printed and true is returned.
2014 std::vector<Record*>
2015 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
2016 Record *Class = getClass(ClassName);
2018 throw "ERROR: Couldn't find the `" + ClassName + "' class!\n";
2020 std::vector<Record*> Defs;
2021 for (std::map<std::string, Record*>::const_iterator I = getDefs().begin(),
2022 E = getDefs().end(); I != E; ++I)
2023 if (I->second->isSubClassOf(Class))
2024 Defs.push_back(I->second);
2029 /// QualifyName - Return an Init with a qualifier prefix referring
2030 /// to CurRec's name.
2031 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2032 Init *Name, const std::string &Scoper) {
2033 RecTy *Type = dynamic_cast<TypedInit *>(Name)->getType();
2035 BinOpInit *NewName =
2036 BinOpInit::get(BinOpInit::STRCONCAT,
2037 BinOpInit::get(BinOpInit::STRCONCAT,
2038 CurRec.getNameInit(),
2039 StringInit::get(Scoper),
2040 Type)->Fold(&CurRec, CurMultiClass),
2044 if (CurMultiClass && Scoper != "::") {
2046 BinOpInit::get(BinOpInit::STRCONCAT,
2047 BinOpInit::get(BinOpInit::STRCONCAT,
2048 CurMultiClass->Rec.getNameInit(),
2049 StringInit::get("::"),
2050 Type)->Fold(&CurRec, CurMultiClass),
2051 NewName->Fold(&CurRec, CurMultiClass),
2055 return NewName->Fold(&CurRec, CurMultiClass);
2058 /// QualifyName - Return an Init with a qualifier prefix referring
2059 /// to CurRec's name.
2060 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2061 const std::string &Name,
2062 const std::string &Scoper) {
2063 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);