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::anchor() { }
85 void RecTy::dump() const { print(errs()); }
87 ListRecTy *RecTy::getListTy() {
89 ListTy = new ListRecTy(this);
93 Init *BitRecTy::convertValue(BitsInit *BI) {
94 if (BI->getNumBits() != 1) return 0; // Only accept if just one bit!
98 bool BitRecTy::baseClassOf(const BitsRecTy *RHS) const {
99 return RHS->getNumBits() == 1;
102 Init *BitRecTy::convertValue(IntInit *II) {
103 int64_t Val = II->getValue();
104 if (Val != 0 && Val != 1) return 0; // Only accept 0 or 1 for a bit!
106 return BitInit::get(Val != 0);
109 Init *BitRecTy::convertValue(TypedInit *VI) {
110 if (dynamic_cast<BitRecTy*>(VI->getType()))
111 return VI; // Accept variable if it is already of bit type!
115 BitsRecTy *BitsRecTy::get(unsigned Sz) {
116 static std::vector<BitsRecTy*> Shared;
117 if (Sz >= Shared.size())
118 Shared.resize(Sz + 1);
119 BitsRecTy *&Ty = Shared[Sz];
121 Ty = new BitsRecTy(Sz);
125 std::string BitsRecTy::getAsString() const {
126 return "bits<" + utostr(Size) + ">";
129 Init *BitsRecTy::convertValue(UnsetInit *UI) {
130 SmallVector<Init *, 16> NewBits(Size);
132 for (unsigned i = 0; i != Size; ++i)
133 NewBits[i] = UnsetInit::get();
135 return BitsInit::get(NewBits);
138 Init *BitsRecTy::convertValue(BitInit *UI) {
139 if (Size != 1) return 0; // Can only convert single bit.
140 return BitsInit::get(UI);
143 /// canFitInBitfield - Return true if the number of bits is large enough to hold
144 /// the integer value.
145 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
146 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
147 return (NumBits >= sizeof(Value) * 8) ||
148 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
151 /// convertValue from Int initializer to bits type: Split the integer up into the
152 /// appropriate bits.
154 Init *BitsRecTy::convertValue(IntInit *II) {
155 int64_t Value = II->getValue();
156 // Make sure this bitfield is large enough to hold the integer value.
157 if (!canFitInBitfield(Value, Size))
160 SmallVector<Init *, 16> NewBits(Size);
162 for (unsigned i = 0; i != Size; ++i)
163 NewBits[i] = BitInit::get(Value & (1LL << i));
165 return BitsInit::get(NewBits);
168 Init *BitsRecTy::convertValue(BitsInit *BI) {
169 // If the number of bits is right, return it. Otherwise we need to expand or
171 if (BI->getNumBits() == Size) return BI;
175 Init *BitsRecTy::convertValue(TypedInit *VI) {
176 if (BitsRecTy *BRT = dynamic_cast<BitsRecTy*>(VI->getType()))
177 if (BRT->Size == Size) {
178 SmallVector<Init *, 16> NewBits(Size);
180 for (unsigned i = 0; i != Size; ++i)
181 NewBits[i] = VarBitInit::get(VI, i);
182 return BitsInit::get(NewBits);
185 if (Size == 1 && dynamic_cast<BitRecTy*>(VI->getType()))
186 return BitsInit::get(VI);
188 if (TernOpInit *Tern = dynamic_cast<TernOpInit*>(VI)) {
189 if (Tern->getOpcode() == TernOpInit::IF) {
190 Init *LHS = Tern->getLHS();
191 Init *MHS = Tern->getMHS();
192 Init *RHS = Tern->getRHS();
194 IntInit *MHSi = dynamic_cast<IntInit*>(MHS);
195 IntInit *RHSi = dynamic_cast<IntInit*>(RHS);
198 int64_t MHSVal = MHSi->getValue();
199 int64_t RHSVal = RHSi->getValue();
201 if (canFitInBitfield(MHSVal, Size) && canFitInBitfield(RHSVal, Size)) {
202 SmallVector<Init *, 16> NewBits(Size);
204 for (unsigned i = 0; i != Size; ++i)
206 TernOpInit::get(TernOpInit::IF, LHS,
207 IntInit::get((MHSVal & (1LL << i)) ? 1 : 0),
208 IntInit::get((RHSVal & (1LL << i)) ? 1 : 0),
211 return BitsInit::get(NewBits);
214 BitsInit *MHSbs = dynamic_cast<BitsInit*>(MHS);
215 BitsInit *RHSbs = dynamic_cast<BitsInit*>(RHS);
217 if (MHSbs && RHSbs) {
218 SmallVector<Init *, 16> NewBits(Size);
220 for (unsigned i = 0; i != Size; ++i)
221 NewBits[i] = TernOpInit::get(TernOpInit::IF, LHS,
226 return BitsInit::get(NewBits);
235 Init *IntRecTy::convertValue(BitInit *BI) {
236 return IntInit::get(BI->getValue());
239 Init *IntRecTy::convertValue(BitsInit *BI) {
241 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
242 if (BitInit *Bit = dynamic_cast<BitInit*>(BI->getBit(i))) {
243 Result |= Bit->getValue() << i;
247 return IntInit::get(Result);
250 Init *IntRecTy::convertValue(TypedInit *TI) {
251 if (TI->getType()->typeIsConvertibleTo(this))
252 return TI; // Accept variable if already of the right type!
256 Init *StringRecTy::convertValue(UnOpInit *BO) {
257 if (BO->getOpcode() == UnOpInit::CAST) {
258 Init *L = BO->getOperand()->convertInitializerTo(this);
259 if (L == 0) return 0;
260 if (L != BO->getOperand())
261 return UnOpInit::get(UnOpInit::CAST, L, new StringRecTy);
265 return convertValue((TypedInit*)BO);
268 Init *StringRecTy::convertValue(BinOpInit *BO) {
269 if (BO->getOpcode() == BinOpInit::STRCONCAT) {
270 Init *L = BO->getLHS()->convertInitializerTo(this);
271 Init *R = BO->getRHS()->convertInitializerTo(this);
272 if (L == 0 || R == 0) return 0;
273 if (L != BO->getLHS() || R != BO->getRHS())
274 return BinOpInit::get(BinOpInit::STRCONCAT, L, R, new StringRecTy);
278 return convertValue((TypedInit*)BO);
282 Init *StringRecTy::convertValue(TypedInit *TI) {
283 if (dynamic_cast<StringRecTy*>(TI->getType()))
284 return TI; // Accept variable if already of the right type!
288 std::string ListRecTy::getAsString() const {
289 return "list<" + Ty->getAsString() + ">";
292 Init *ListRecTy::convertValue(ListInit *LI) {
293 std::vector<Init*> Elements;
295 // Verify that all of the elements of the list are subclasses of the
296 // appropriate class!
297 for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
298 if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
299 Elements.push_back(CI);
303 ListRecTy *LType = dynamic_cast<ListRecTy*>(LI->getType());
308 return ListInit::get(Elements, this);
311 Init *ListRecTy::convertValue(TypedInit *TI) {
312 // Ensure that TI is compatible with our class.
313 if (ListRecTy *LRT = dynamic_cast<ListRecTy*>(TI->getType()))
314 if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
319 Init *CodeRecTy::convertValue(TypedInit *TI) {
320 if (TI->getType()->typeIsConvertibleTo(this))
325 Init *DagRecTy::convertValue(TypedInit *TI) {
326 if (TI->getType()->typeIsConvertibleTo(this))
331 Init *DagRecTy::convertValue(UnOpInit *BO) {
332 if (BO->getOpcode() == UnOpInit::CAST) {
333 Init *L = BO->getOperand()->convertInitializerTo(this);
334 if (L == 0) return 0;
335 if (L != BO->getOperand())
336 return UnOpInit::get(UnOpInit::CAST, L, new DagRecTy);
342 Init *DagRecTy::convertValue(BinOpInit *BO) {
343 if (BO->getOpcode() == BinOpInit::CONCAT) {
344 Init *L = BO->getLHS()->convertInitializerTo(this);
345 Init *R = BO->getRHS()->convertInitializerTo(this);
346 if (L == 0 || R == 0) return 0;
347 if (L != BO->getLHS() || R != BO->getRHS())
348 return BinOpInit::get(BinOpInit::CONCAT, L, R, new DagRecTy);
354 RecordRecTy *RecordRecTy::get(Record *R) {
355 return &dynamic_cast<RecordRecTy&>(*R->getDefInit()->getType());
358 std::string RecordRecTy::getAsString() const {
359 return Rec->getName();
362 Init *RecordRecTy::convertValue(DefInit *DI) {
363 // Ensure that DI is a subclass of Rec.
364 if (!DI->getDef()->isSubClassOf(Rec))
369 Init *RecordRecTy::convertValue(TypedInit *TI) {
370 // Ensure that TI is compatible with Rec.
371 if (RecordRecTy *RRT = dynamic_cast<RecordRecTy*>(TI->getType()))
372 if (RRT->getRecord()->isSubClassOf(getRecord()) ||
373 RRT->getRecord() == getRecord())
378 bool RecordRecTy::baseClassOf(const RecordRecTy *RHS) const {
379 if (Rec == RHS->getRecord() || RHS->getRecord()->isSubClassOf(Rec))
382 const std::vector<Record*> &SC = Rec->getSuperClasses();
383 for (unsigned i = 0, e = SC.size(); i != e; ++i)
384 if (RHS->getRecord()->isSubClassOf(SC[i]))
391 /// resolveTypes - Find a common type that T1 and T2 convert to.
392 /// Return 0 if no such type exists.
394 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
395 if (!T1->typeIsConvertibleTo(T2)) {
396 if (!T2->typeIsConvertibleTo(T1)) {
397 // If one is a Record type, check superclasses
398 RecordRecTy *RecTy1 = dynamic_cast<RecordRecTy*>(T1);
400 // See if T2 inherits from a type T1 also inherits from
401 const std::vector<Record *> &T1SuperClasses =
402 RecTy1->getRecord()->getSuperClasses();
403 for(std::vector<Record *>::const_iterator i = T1SuperClasses.begin(),
404 iend = T1SuperClasses.end();
407 RecordRecTy *SuperRecTy1 = RecordRecTy::get(*i);
408 RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
410 if (NewType1 != SuperRecTy1) {
417 RecordRecTy *RecTy2 = dynamic_cast<RecordRecTy*>(T2);
419 // See if T1 inherits from a type T2 also inherits from
420 const std::vector<Record *> &T2SuperClasses =
421 RecTy2->getRecord()->getSuperClasses();
422 for (std::vector<Record *>::const_iterator i = T2SuperClasses.begin(),
423 iend = T2SuperClasses.end();
426 RecordRecTy *SuperRecTy2 = RecordRecTy::get(*i);
427 RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
429 if (NewType2 != SuperRecTy2) {
444 //===----------------------------------------------------------------------===//
445 // Initializer implementations
446 //===----------------------------------------------------------------------===//
448 void Init::anchor() { }
449 void Init::dump() const { return print(errs()); }
451 void UnsetInit::anchor() { }
453 UnsetInit *UnsetInit::get() {
454 static UnsetInit TheInit;
458 void BitInit::anchor() { }
460 BitInit *BitInit::get(bool V) {
461 static BitInit True(true);
462 static BitInit False(false);
464 return V ? &True : &False;
468 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
469 ID.AddInteger(Range.size());
471 for (ArrayRef<Init *>::iterator i = Range.begin(),
478 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
479 typedef FoldingSet<BitsInit> Pool;
483 ProfileBitsInit(ID, Range);
486 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
489 BitsInit *I = new BitsInit(Range);
490 ThePool.InsertNode(I, IP);
495 void BitsInit::Profile(FoldingSetNodeID &ID) const {
496 ProfileBitsInit(ID, Bits);
500 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
501 SmallVector<Init *, 16> NewBits(Bits.size());
503 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
504 if (Bits[i] >= getNumBits())
506 NewBits[i] = getBit(Bits[i]);
508 return BitsInit::get(NewBits);
511 std::string BitsInit::getAsString() const {
512 std::string Result = "{ ";
513 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
514 if (i) Result += ", ";
515 if (Init *Bit = getBit(e-i-1))
516 Result += Bit->getAsString();
520 return Result + " }";
523 // resolveReferences - If there are any field references that refer to fields
524 // that have been filled in, we can propagate the values now.
526 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
527 bool Changed = false;
528 SmallVector<Init *, 16> NewBits(getNumBits());
530 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
532 Init *CurBit = getBit(i);
536 CurBit = CurBit->resolveReferences(R, RV);
537 Changed |= B != CurBit;
538 } while (B != CurBit);
543 return BitsInit::get(NewBits);
545 return const_cast<BitsInit *>(this);
548 IntInit *IntInit::get(int64_t V) {
549 typedef DenseMap<int64_t, IntInit *> Pool;
552 IntInit *&I = ThePool[V];
553 if (!I) I = new IntInit(V);
557 std::string IntInit::getAsString() const {
558 return itostr(Value);
562 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
563 SmallVector<Init *, 16> NewBits(Bits.size());
565 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
569 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
571 return BitsInit::get(NewBits);
574 void StringInit::anchor() { }
576 StringInit *StringInit::get(const std::string &V) {
577 typedef StringMap<StringInit *> Pool;
580 StringInit *&I = ThePool[V];
581 if (!I) I = new StringInit(V);
585 void CodeInit::anchor() { }
587 CodeInit *CodeInit::get(const std::string &V) {
588 typedef StringMap<CodeInit *> Pool;
591 CodeInit *&I = ThePool[V];
592 if (!I) I = new CodeInit(V);
596 static void ProfileListInit(FoldingSetNodeID &ID,
597 ArrayRef<Init *> Range,
599 ID.AddInteger(Range.size());
600 ID.AddPointer(EltTy);
602 for (ArrayRef<Init *>::iterator i = Range.begin(),
609 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
610 typedef FoldingSet<ListInit> Pool;
613 // Just use the FoldingSetNodeID to compute a hash. Use a DenseMap
614 // for actual storage.
616 ProfileListInit(ID, Range, EltTy);
619 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
622 ListInit *I = new ListInit(Range, EltTy);
623 ThePool.InsertNode(I, IP);
627 void ListInit::Profile(FoldingSetNodeID &ID) const {
628 ListRecTy *ListType = dynamic_cast<ListRecTy *>(getType());
629 assert(ListType && "Bad type for ListInit!");
630 RecTy *EltTy = ListType->getElementType();
632 ProfileListInit(ID, Values, EltTy);
636 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
637 std::vector<Init*> Vals;
638 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
639 if (Elements[i] >= getSize())
641 Vals.push_back(getElement(Elements[i]));
643 return ListInit::get(Vals, getType());
646 Record *ListInit::getElementAsRecord(unsigned i) const {
647 assert(i < Values.size() && "List element index out of range!");
648 DefInit *DI = dynamic_cast<DefInit*>(Values[i]);
649 if (DI == 0) throw "Expected record in list!";
653 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
654 std::vector<Init*> Resolved;
655 Resolved.reserve(getSize());
656 bool Changed = false;
658 for (unsigned i = 0, e = getSize(); i != e; ++i) {
660 Init *CurElt = getElement(i);
664 CurElt = CurElt->resolveReferences(R, RV);
665 Changed |= E != CurElt;
666 } while (E != CurElt);
667 Resolved.push_back(E);
671 return ListInit::get(Resolved, getType());
672 return const_cast<ListInit *>(this);
675 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
676 unsigned Elt) const {
677 if (Elt >= getSize())
678 return 0; // Out of range reference.
679 Init *E = getElement(Elt);
680 // If the element is set to some value, or if we are resolving a reference
681 // to a specific variable and that variable is explicitly unset, then
682 // replace the VarListElementInit with it.
683 if (IRV || !dynamic_cast<UnsetInit*>(E))
688 std::string ListInit::getAsString() const {
689 std::string Result = "[";
690 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
691 if (i) Result += ", ";
692 Result += Values[i]->getAsString();
697 Init *OpInit::resolveBitReference(Record &R, const RecordVal *IRV,
698 unsigned Bit) const {
699 Init *Folded = Fold(&R, 0);
701 if (Folded != this) {
702 TypedInit *Typed = dynamic_cast<TypedInit *>(Folded);
704 return Typed->resolveBitReference(R, IRV, Bit);
711 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
712 unsigned Elt) const {
713 Init *Resolved = resolveReferences(R, IRV);
714 OpInit *OResolved = dynamic_cast<OpInit *>(Resolved);
716 Resolved = OResolved->Fold(&R, 0);
719 if (Resolved != this) {
720 TypedInit *Typed = dynamic_cast<TypedInit *>(Resolved);
721 assert(Typed && "Expected typed init for list reference");
723 Init *New = Typed->resolveListElementReference(R, IRV, Elt);
726 return VarListElementInit::get(Typed, Elt);
733 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
734 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
736 typedef DenseMap<Key, UnOpInit *> Pool;
739 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
741 UnOpInit *&I = ThePool[TheKey];
742 if (!I) I = new UnOpInit(opc, lhs, Type);
746 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
747 switch (getOpcode()) {
748 default: assert(0 && "Unknown unop");
750 if (getType()->getAsString() == "string") {
751 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
756 DefInit *LHSd = dynamic_cast<DefInit*>(LHS);
758 return StringInit::get(LHSd->getDef()->getName());
761 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
763 std::string Name = LHSs->getValue();
765 // From TGParser::ParseIDValue
767 if (const RecordVal *RV = CurRec->getValue(Name)) {
768 if (RV->getType() != getType())
769 throw "type mismatch in cast";
770 return VarInit::get(Name, RV->getType());
773 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
776 if (CurRec->isTemplateArg(TemplateArgName)) {
777 const RecordVal *RV = CurRec->getValue(TemplateArgName);
778 assert(RV && "Template arg doesn't exist??");
780 if (RV->getType() != getType())
781 throw "type mismatch in cast";
783 return VarInit::get(TemplateArgName, RV->getType());
788 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
790 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
791 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
792 assert(RV && "Template arg doesn't exist??");
794 if (RV->getType() != getType())
795 throw "type mismatch in cast";
797 return VarInit::get(MCName, RV->getType());
801 if (Record *D = (CurRec->getRecords()).getDef(Name))
802 return DefInit::get(D);
804 throw TGError(CurRec->getLoc(), "Undefined reference:'" + Name + "'\n");
810 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
812 if (LHSl->getSize() == 0) {
813 assert(0 && "Empty list in car");
816 return LHSl->getElement(0);
821 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
823 if (LHSl->getSize() == 0) {
824 assert(0 && "Empty list in cdr");
827 // Note the +1. We can't just pass the result of getValues()
829 ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
830 ArrayRef<Init *>::iterator end = LHSl->getValues().end();
832 ListInit::get(ArrayRef<Init *>(begin, end - begin),
839 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
841 if (LHSl->getSize() == 0) {
842 return IntInit::get(1);
844 return IntInit::get(0);
847 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
849 if (LHSs->getValue().empty()) {
850 return IntInit::get(1);
852 return IntInit::get(0);
859 return const_cast<UnOpInit *>(this);
862 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
863 Init *lhs = LHS->resolveReferences(R, RV);
866 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, 0);
870 std::string UnOpInit::getAsString() const {
873 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
874 case HEAD: Result = "!head"; break;
875 case TAIL: Result = "!tail"; break;
876 case EMPTY: Result = "!empty"; break;
878 return Result + "(" + LHS->getAsString() + ")";
881 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
882 Init *rhs, RecTy *Type) {
884 std::pair<std::pair<unsigned, Init *>, Init *>,
888 typedef DenseMap<Key, BinOpInit *> Pool;
891 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
894 BinOpInit *&I = ThePool[TheKey];
895 if (!I) I = new BinOpInit(opc, lhs, rhs, Type);
899 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
900 switch (getOpcode()) {
901 default: assert(0 && "Unknown binop");
903 DagInit *LHSs = dynamic_cast<DagInit*>(LHS);
904 DagInit *RHSs = dynamic_cast<DagInit*>(RHS);
906 DefInit *LOp = dynamic_cast<DefInit*>(LHSs->getOperator());
907 DefInit *ROp = dynamic_cast<DefInit*>(RHSs->getOperator());
908 if (LOp == 0 || ROp == 0 || LOp->getDef() != ROp->getDef())
909 throw "Concated Dag operators do not match!";
910 std::vector<Init*> Args;
911 std::vector<std::string> ArgNames;
912 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
913 Args.push_back(LHSs->getArg(i));
914 ArgNames.push_back(LHSs->getArgName(i));
916 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
917 Args.push_back(RHSs->getArg(i));
918 ArgNames.push_back(RHSs->getArgName(i));
920 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
925 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
926 StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
928 return StringInit::get(LHSs->getValue() + RHSs->getValue());
932 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
933 // to string objects.
935 dynamic_cast<IntInit*>(LHS->convertInitializerTo(IntRecTy::get()));
937 dynamic_cast<IntInit*>(RHS->convertInitializerTo(IntRecTy::get()));
940 return IntInit::get(L->getValue() == R->getValue());
942 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
943 StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
945 // Make sure we've resolved
947 return IntInit::get(LHSs->getValue() == RHSs->getValue());
954 IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
955 IntInit *RHSi = dynamic_cast<IntInit*>(RHS);
957 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
959 switch (getOpcode()) {
960 default: assert(0 && "Bad opcode!");
961 case SHL: Result = LHSv << RHSv; break;
962 case SRA: Result = LHSv >> RHSv; break;
963 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
965 return IntInit::get(Result);
970 return const_cast<BinOpInit *>(this);
973 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
974 Init *lhs = LHS->resolveReferences(R, RV);
975 Init *rhs = RHS->resolveReferences(R, RV);
977 if (LHS != lhs || RHS != rhs)
978 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R, 0);
982 std::string BinOpInit::getAsString() const {
985 case CONCAT: Result = "!con"; break;
986 case SHL: Result = "!shl"; break;
987 case SRA: Result = "!sra"; break;
988 case SRL: Result = "!srl"; break;
989 case EQ: Result = "!eq"; break;
990 case STRCONCAT: Result = "!strconcat"; break;
992 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
995 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs,
996 Init *mhs, Init *rhs,
1000 std::pair<std::pair<unsigned, RecTy *>, Init *>,
1006 typedef DenseMap<Key, TernOpInit *> Pool;
1007 static Pool ThePool;
1009 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
1015 TernOpInit *&I = ThePool[TheKey];
1016 if (!I) I = new TernOpInit(opc, lhs, mhs, rhs, Type);
1020 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1021 Record *CurRec, MultiClass *CurMultiClass);
1023 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
1024 RecTy *Type, Record *CurRec,
1025 MultiClass *CurMultiClass) {
1026 std::vector<Init *> NewOperands;
1028 TypedInit *TArg = dynamic_cast<TypedInit*>(Arg);
1030 // If this is a dag, recurse
1031 if (TArg && TArg->getType()->getAsString() == "dag") {
1032 Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
1033 CurRec, CurMultiClass);
1041 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
1042 OpInit *RHSoo = dynamic_cast<OpInit*>(RHSo->getOperand(i));
1045 Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1046 Type, CurRec, CurMultiClass);
1048 NewOperands.push_back(Result);
1050 NewOperands.push_back(Arg);
1052 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1053 NewOperands.push_back(Arg);
1055 NewOperands.push_back(RHSo->getOperand(i));
1059 // Now run the operator and use its result as the new leaf
1060 const OpInit *NewOp = RHSo->clone(NewOperands);
1061 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
1062 if (NewVal != NewOp)
1068 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1069 Record *CurRec, MultiClass *CurMultiClass) {
1070 DagInit *MHSd = dynamic_cast<DagInit*>(MHS);
1071 ListInit *MHSl = dynamic_cast<ListInit*>(MHS);
1073 DagRecTy *DagType = dynamic_cast<DagRecTy*>(Type);
1074 ListRecTy *ListType = dynamic_cast<ListRecTy*>(Type);
1076 OpInit *RHSo = dynamic_cast<OpInit*>(RHS);
1079 throw TGError(CurRec->getLoc(), "!foreach requires an operator\n");
1082 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
1085 throw TGError(CurRec->getLoc(), "!foreach requires typed variable\n");
1088 if ((MHSd && DagType) || (MHSl && ListType)) {
1090 Init *Val = MHSd->getOperator();
1091 Init *Result = EvaluateOperation(RHSo, LHS, Val,
1092 Type, CurRec, CurMultiClass);
1097 std::vector<std::pair<Init *, std::string> > args;
1098 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1100 std::string ArgName;
1101 Arg = MHSd->getArg(i);
1102 ArgName = MHSd->getArgName(i);
1105 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1106 CurRec, CurMultiClass);
1111 // TODO: Process arg names
1112 args.push_back(std::make_pair(Arg, ArgName));
1115 return DagInit::get(Val, "", args);
1118 std::vector<Init *> NewOperands;
1119 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1121 for (std::vector<Init *>::iterator li = NewList.begin(),
1122 liend = NewList.end();
1126 NewOperands.clear();
1127 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1128 // First, replace the foreach variable with the list item
1129 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1130 NewOperands.push_back(Item);
1132 NewOperands.push_back(RHSo->getOperand(i));
1136 // Now run the operator and use its result as the new list item
1137 const OpInit *NewOp = RHSo->clone(NewOperands);
1138 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1139 if (NewItem != NewOp)
1142 return ListInit::get(NewList, MHSl->getType());
1148 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1149 switch (getOpcode()) {
1150 default: assert(0 && "Unknown binop");
1152 DefInit *LHSd = dynamic_cast<DefInit*>(LHS);
1153 VarInit *LHSv = dynamic_cast<VarInit*>(LHS);
1154 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
1156 DefInit *MHSd = dynamic_cast<DefInit*>(MHS);
1157 VarInit *MHSv = dynamic_cast<VarInit*>(MHS);
1158 StringInit *MHSs = dynamic_cast<StringInit*>(MHS);
1160 DefInit *RHSd = dynamic_cast<DefInit*>(RHS);
1161 VarInit *RHSv = dynamic_cast<VarInit*>(RHS);
1162 StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
1164 if ((LHSd && MHSd && RHSd)
1165 || (LHSv && MHSv && RHSv)
1166 || (LHSs && MHSs && RHSs)) {
1168 Record *Val = RHSd->getDef();
1169 if (LHSd->getAsString() == RHSd->getAsString()) {
1170 Val = MHSd->getDef();
1172 return DefInit::get(Val);
1175 std::string Val = RHSv->getName();
1176 if (LHSv->getAsString() == RHSv->getAsString()) {
1177 Val = MHSv->getName();
1179 return VarInit::get(Val, getType());
1182 std::string Val = RHSs->getValue();
1184 std::string::size_type found;
1185 std::string::size_type idx = 0;
1187 found = Val.find(LHSs->getValue(), idx);
1188 if (found != std::string::npos) {
1189 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1191 idx = found + MHSs->getValue().size();
1192 } while (found != std::string::npos);
1194 return StringInit::get(Val);
1201 Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1202 CurRec, CurMultiClass);
1210 IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
1211 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1212 LHSi = dynamic_cast<IntInit*>(I);
1214 if (LHSi->getValue()) {
1224 return const_cast<TernOpInit *>(this);
1227 Init *TernOpInit::resolveReferences(Record &R,
1228 const RecordVal *RV) const {
1229 Init *lhs = LHS->resolveReferences(R, RV);
1231 if (Opc == IF && lhs != LHS) {
1232 IntInit *Value = dynamic_cast<IntInit*>(lhs);
1233 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1234 Value = dynamic_cast<IntInit*>(I);
1237 if (Value->getValue()) {
1238 Init *mhs = MHS->resolveReferences(R, RV);
1239 return (TernOpInit::get(getOpcode(), lhs, mhs,
1240 RHS, getType()))->Fold(&R, 0);
1242 Init *rhs = RHS->resolveReferences(R, RV);
1243 return (TernOpInit::get(getOpcode(), lhs, MHS,
1244 rhs, getType()))->Fold(&R, 0);
1249 Init *mhs = MHS->resolveReferences(R, RV);
1250 Init *rhs = RHS->resolveReferences(R, RV);
1252 if (LHS != lhs || MHS != mhs || RHS != rhs)
1253 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1254 getType()))->Fold(&R, 0);
1258 std::string TernOpInit::getAsString() const {
1261 case SUBST: Result = "!subst"; break;
1262 case FOREACH: Result = "!foreach"; break;
1263 case IF: Result = "!if"; break;
1265 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
1266 + RHS->getAsString() + ")";
1269 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1270 RecordRecTy *RecordType = dynamic_cast<RecordRecTy *>(getType());
1272 RecordVal *Field = RecordType->getRecord()->getValue(FieldName);
1274 return Field->getType();
1281 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1282 BitsRecTy *T = dynamic_cast<BitsRecTy*>(getType());
1283 if (T == 0) return 0; // Cannot subscript a non-bits variable.
1284 unsigned NumBits = T->getNumBits();
1286 SmallVector<Init *, 16> NewBits(Bits.size());
1287 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1288 if (Bits[i] >= NumBits)
1291 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1293 return BitsInit::get(NewBits);
1297 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1298 ListRecTy *T = dynamic_cast<ListRecTy*>(getType());
1299 if (T == 0) return 0; // Cannot subscript a non-list variable.
1301 if (Elements.size() == 1)
1302 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1304 std::vector<Init*> ListInits;
1305 ListInits.reserve(Elements.size());
1306 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1307 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1309 return ListInit::get(ListInits, T);
1313 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1314 Init *Value = StringInit::get(VN);
1315 return VarInit::get(Value, T);
1318 VarInit *VarInit::get(Init *VN, RecTy *T) {
1319 typedef std::pair<RecTy *, Init *> Key;
1320 typedef DenseMap<Key, VarInit *> Pool;
1321 static Pool ThePool;
1323 Key TheKey(std::make_pair(T, VN));
1325 VarInit *&I = ThePool[TheKey];
1326 if (!I) I = new VarInit(VN, T);
1330 const std::string &VarInit::getName() const {
1331 StringInit *NameString =
1332 dynamic_cast<StringInit *>(getNameInit());
1333 assert(NameString && "VarInit name is not a string!");
1334 return NameString->getValue();
1337 Init *VarInit::resolveBitReference(Record &R, const RecordVal *IRV,
1338 unsigned Bit) const {
1339 if (R.isTemplateArg(getName())) return 0;
1340 if (IRV && IRV->getName() != getName()) return 0;
1342 RecordVal *RV = R.getValue(getName());
1343 assert(RV && "Reference to a non-existent variable?");
1344 assert(dynamic_cast<BitsInit*>(RV->getValue()));
1345 BitsInit *BI = (BitsInit*)RV->getValue();
1347 assert(Bit < BI->getNumBits() && "Bit reference out of range!");
1348 Init *B = BI->getBit(Bit);
1350 // If the bit is set to some value, or if we are resolving a reference to a
1351 // specific variable and that variable is explicitly unset, then replace the
1352 // VarBitInit with it.
1353 if (IRV || !dynamic_cast<UnsetInit*>(B))
1358 Init *VarInit::resolveListElementReference(Record &R,
1359 const RecordVal *IRV,
1360 unsigned Elt) const {
1361 if (R.isTemplateArg(getName())) return 0;
1362 if (IRV && IRV->getName() != getName()) return 0;
1364 RecordVal *RV = R.getValue(getName());
1365 assert(RV && "Reference to a non-existent variable?");
1366 ListInit *LI = dynamic_cast<ListInit*>(RV->getValue());
1368 TypedInit *VI = dynamic_cast<TypedInit*>(RV->getValue());
1369 assert(VI && "Invalid list element!");
1370 return VarListElementInit::get(VI, Elt);
1373 if (Elt >= LI->getSize())
1374 return 0; // Out of range reference.
1375 Init *E = LI->getElement(Elt);
1376 // If the element is set to some value, or if we are resolving a reference
1377 // to a specific variable and that variable is explicitly unset, then
1378 // replace the VarListElementInit with it.
1379 if (IRV || !dynamic_cast<UnsetInit*>(E))
1385 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1386 if (RecordRecTy *RTy = dynamic_cast<RecordRecTy*>(getType()))
1387 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1388 return RV->getType();
1392 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1393 const std::string &FieldName) const {
1394 if (dynamic_cast<RecordRecTy*>(getType()))
1395 if (const RecordVal *Val = R.getValue(VarName)) {
1396 if (RV != Val && (RV || dynamic_cast<UnsetInit*>(Val->getValue())))
1398 Init *TheInit = Val->getValue();
1399 assert(TheInit != this && "Infinite loop detected!");
1400 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1408 /// resolveReferences - This method is used by classes that refer to other
1409 /// variables which may not be defined at the time the expression is formed.
1410 /// If a value is set for the variable later, this method will be called on
1411 /// users of the value to allow the value to propagate out.
1413 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1414 if (RecordVal *Val = R.getValue(VarName))
1415 if (RV == Val || (RV == 0 && !dynamic_cast<UnsetInit*>(Val->getValue())))
1416 return Val->getValue();
1417 return const_cast<VarInit *>(this);
1420 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1421 typedef std::pair<TypedInit *, unsigned> Key;
1422 typedef DenseMap<Key, VarBitInit *> Pool;
1424 static Pool ThePool;
1426 Key TheKey(std::make_pair(T, B));
1428 VarBitInit *&I = ThePool[TheKey];
1429 if (!I) I = new VarBitInit(T, B);
1433 std::string VarBitInit::getAsString() const {
1434 return TI->getAsString() + "{" + utostr(Bit) + "}";
1437 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1438 if (Init *I = getVariable()->resolveBitReference(R, RV, getBitNum()))
1440 return const_cast<VarBitInit *>(this);
1443 VarListElementInit *VarListElementInit::get(TypedInit *T,
1445 typedef std::pair<TypedInit *, unsigned> Key;
1446 typedef DenseMap<Key, VarListElementInit *> Pool;
1448 static Pool ThePool;
1450 Key TheKey(std::make_pair(T, E));
1452 VarListElementInit *&I = ThePool[TheKey];
1453 if (!I) I = new VarListElementInit(T, E);
1457 std::string VarListElementInit::getAsString() const {
1458 return TI->getAsString() + "[" + utostr(Element) + "]";
1462 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1463 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1466 return const_cast<VarListElementInit *>(this);
1469 Init *VarListElementInit::resolveBitReference(Record &R, const RecordVal *RV,
1470 unsigned Bit) const {
1471 // FIXME: This should be implemented, to support references like:
1472 // bit B = AA[0]{1};
1476 Init *VarListElementInit:: resolveListElementReference(Record &R,
1477 const RecordVal *RV,
1478 unsigned Elt) const {
1479 Init *Result = TI->resolveListElementReference(R, RV, Element);
1482 TypedInit *TInit = dynamic_cast<TypedInit *>(Result);
1484 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1485 if (Result2) return Result2;
1486 return new VarListElementInit(TInit, Elt);
1494 DefInit *DefInit::get(Record *R) {
1495 return R->getDefInit();
1498 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1499 if (const RecordVal *RV = Def->getValue(FieldName))
1500 return RV->getType();
1504 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1505 const std::string &FieldName) const {
1506 return Def->getValue(FieldName)->getValue();
1510 std::string DefInit::getAsString() const {
1511 return Def->getName();
1514 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1515 typedef std::pair<Init *, TableGenStringKey> Key;
1516 typedef DenseMap<Key, FieldInit *> Pool;
1517 static Pool ThePool;
1519 Key TheKey(std::make_pair(R, FN));
1521 FieldInit *&I = ThePool[TheKey];
1522 if (!I) I = new FieldInit(R, FN);
1526 Init *FieldInit::resolveBitReference(Record &R, const RecordVal *RV,
1527 unsigned Bit) const {
1528 if (Init *BitsVal = Rec->getFieldInit(R, RV, FieldName))
1529 if (BitsInit *BI = dynamic_cast<BitsInit*>(BitsVal)) {
1530 assert(Bit < BI->getNumBits() && "Bit reference out of range!");
1531 Init *B = BI->getBit(Bit);
1533 if (dynamic_cast<BitInit*>(B)) // If the bit is set.
1534 return B; // Replace the VarBitInit with it.
1539 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1540 unsigned Elt) const {
1541 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1542 if (ListInit *LI = dynamic_cast<ListInit*>(ListVal)) {
1543 if (Elt >= LI->getSize()) return 0;
1544 Init *E = LI->getElement(Elt);
1546 // If the element is set to some value, or if we are resolving a
1547 // reference to a specific variable and that variable is explicitly
1548 // unset, then replace the VarListElementInit with it.
1549 if (RV || !dynamic_cast<UnsetInit*>(E))
1555 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1556 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1558 Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1560 Init *BVR = BitsVal->resolveReferences(R, RV);
1561 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1564 if (NewRec != Rec) {
1565 return FieldInit::get(NewRec, FieldName);
1567 return const_cast<FieldInit *>(this);
1570 void ProfileDagInit(FoldingSetNodeID &ID,
1572 const std::string &VN,
1573 ArrayRef<Init *> ArgRange,
1574 ArrayRef<std::string> NameRange) {
1578 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1579 ArrayRef<std::string>::iterator Name = NameRange.begin();
1580 while (Arg != ArgRange.end()) {
1581 assert(Name != NameRange.end() && "Arg name underflow!");
1582 ID.AddPointer(*Arg++);
1583 ID.AddString(*Name++);
1585 assert(Name == NameRange.end() && "Arg name overflow!");
1589 DagInit::get(Init *V, const std::string &VN,
1590 ArrayRef<Init *> ArgRange,
1591 ArrayRef<std::string> NameRange) {
1592 typedef FoldingSet<DagInit> Pool;
1593 static Pool ThePool;
1595 FoldingSetNodeID ID;
1596 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1599 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1602 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1603 ThePool.InsertNode(I, IP);
1609 DagInit::get(Init *V, const std::string &VN,
1610 const std::vector<std::pair<Init*, std::string> > &args) {
1611 typedef std::pair<Init*, std::string> PairType;
1613 std::vector<Init *> Args;
1614 std::vector<std::string> Names;
1616 for (std::vector<PairType>::const_iterator i = args.begin(),
1620 Args.push_back(i->first);
1621 Names.push_back(i->second);
1624 return DagInit::get(V, VN, Args, Names);
1627 void DagInit::Profile(FoldingSetNodeID &ID) const {
1628 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1631 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1632 std::vector<Init*> NewArgs;
1633 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1634 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1636 Init *Op = Val->resolveReferences(R, RV);
1638 if (Args != NewArgs || Op != Val)
1639 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1641 return const_cast<DagInit *>(this);
1645 std::string DagInit::getAsString() const {
1646 std::string Result = "(" + Val->getAsString();
1647 if (!ValName.empty())
1648 Result += ":" + ValName;
1650 Result += " " + Args[0]->getAsString();
1651 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1652 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1653 Result += ", " + Args[i]->getAsString();
1654 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1657 return Result + ")";
1661 //===----------------------------------------------------------------------===//
1662 // Other implementations
1663 //===----------------------------------------------------------------------===//
1665 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1666 : Name(N), Ty(T), Prefix(P) {
1667 Value = Ty->convertValue(UnsetInit::get());
1668 assert(Value && "Cannot create unset value for current type!");
1671 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1672 : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1673 Value = Ty->convertValue(UnsetInit::get());
1674 assert(Value && "Cannot create unset value for current type!");
1677 const std::string &RecordVal::getName() const {
1678 StringInit *NameString = dynamic_cast<StringInit *>(Name);
1679 assert(NameString && "RecordVal name is not a string!");
1680 return NameString->getValue();
1683 void RecordVal::dump() const { errs() << *this; }
1685 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1686 if (getPrefix()) OS << "field ";
1687 OS << *getType() << " " << getNameInitAsString();
1690 OS << " = " << *getValue();
1692 if (PrintSem) OS << ";\n";
1695 unsigned Record::LastID = 0;
1697 void Record::init() {
1700 // Every record potentially has a def at the top. This value is
1701 // replaced with the top-level def name at instantiation time.
1702 RecordVal DN("NAME", StringRecTy::get(), 0);
1706 void Record::checkName() {
1707 // Ensure the record name has string type.
1708 const TypedInit *TypedName = dynamic_cast<const TypedInit *>(Name);
1709 assert(TypedName && "Record name is not typed!");
1710 RecTy *Type = TypedName->getType();
1711 if (dynamic_cast<StringRecTy *>(Type) == 0) {
1712 throw "Record name is not a string!";
1716 DefInit *Record::getDefInit() {
1718 TheInit = new DefInit(this, new RecordRecTy(this));
1722 const std::string &Record::getName() const {
1723 const StringInit *NameString =
1724 dynamic_cast<const StringInit *>(Name);
1725 assert(NameString && "Record name is not a string!");
1726 return NameString->getValue();
1729 void Record::setName(Init *NewName) {
1730 if (TrackedRecords.getDef(Name->getAsUnquotedString()) == this) {
1731 TrackedRecords.removeDef(Name->getAsUnquotedString());
1732 TrackedRecords.addDef(this);
1733 } else if (TrackedRecords.getClass(Name->getAsUnquotedString()) == this) {
1734 TrackedRecords.removeClass(Name->getAsUnquotedString());
1735 TrackedRecords.addClass(this);
1736 } // Otherwise this isn't yet registered.
1739 // Since the Init for the name was changed, see if we can resolve
1740 // any of it using members of the Record.
1741 Init *ComputedName = Name->resolveReferences(*this, 0);
1742 if (ComputedName != Name) {
1743 setName(ComputedName);
1745 // DO NOT resolve record values to the name at this point because
1746 // there might be default values for arguments of this def. Those
1747 // arguments might not have been resolved yet so we don't want to
1748 // prematurely assume values for those arguments were not passed to
1751 // Nonetheless, it may be that some of this Record's values
1752 // reference the record name. Indeed, the reason for having the
1753 // record name be an Init is to provide this flexibility. The extra
1754 // resolve steps after completely instantiating defs takes care of
1755 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1758 void Record::setName(const std::string &Name) {
1759 setName(StringInit::get(Name));
1762 const RecordVal *Record::getValue(Init *Name) const {
1763 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1764 if (Values[i].getNameInit() == Name) return &Values[i];
1768 RecordVal *Record::getValue(Init *Name) {
1769 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1770 if (Values[i].getNameInit() == Name) return &Values[i];
1774 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1775 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1777 void Record::resolveReferencesTo(const RecordVal *RV) {
1778 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1779 if (Init *V = Values[i].getValue())
1780 Values[i].setValue(V->resolveReferences(*this, RV));
1782 Init *OldName = getNameInit();
1783 Init *NewName = Name->resolveReferences(*this, RV);
1784 if (NewName != OldName) {
1785 // Re-register with RecordKeeper.
1790 void Record::dump() const { errs() << *this; }
1792 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1793 OS << R.getNameInitAsString();
1795 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1796 if (!TArgs.empty()) {
1798 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1800 const RecordVal *RV = R.getValue(TArgs[i]);
1801 assert(RV && "Template argument record not found??");
1802 RV->print(OS, false);
1808 const std::vector<Record*> &SC = R.getSuperClasses();
1811 for (unsigned i = 0, e = SC.size(); i != e; ++i)
1812 OS << " " << SC[i]->getNameInitAsString();
1816 const std::vector<RecordVal> &Vals = R.getValues();
1817 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1818 if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1820 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1821 if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1827 /// getValueInit - Return the initializer for a value with the specified name,
1828 /// or throw an exception if the field does not exist.
1830 Init *Record::getValueInit(StringRef FieldName) const {
1831 const RecordVal *R = getValue(FieldName);
1832 if (R == 0 || R->getValue() == 0)
1833 throw "Record `" + getName() + "' does not have a field named `" +
1834 FieldName.str() + "'!\n";
1835 return R->getValue();
1839 /// getValueAsString - This method looks up the specified field and returns its
1840 /// value as a string, throwing an exception if the field does not exist or if
1841 /// the value is not a string.
1843 std::string Record::getValueAsString(StringRef FieldName) const {
1844 const RecordVal *R = getValue(FieldName);
1845 if (R == 0 || R->getValue() == 0)
1846 throw "Record `" + getName() + "' does not have a field named `" +
1847 FieldName.str() + "'!\n";
1849 if (StringInit *SI = dynamic_cast<StringInit*>(R->getValue()))
1850 return SI->getValue();
1851 throw "Record `" + getName() + "', field `" + FieldName.str() +
1852 "' does not have a string initializer!";
1855 /// getValueAsBitsInit - This method looks up the specified field and returns
1856 /// its value as a BitsInit, throwing an exception if the field does not exist
1857 /// or if the value is not the right type.
1859 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1860 const RecordVal *R = getValue(FieldName);
1861 if (R == 0 || R->getValue() == 0)
1862 throw "Record `" + getName() + "' does not have a field named `" +
1863 FieldName.str() + "'!\n";
1865 if (BitsInit *BI = dynamic_cast<BitsInit*>(R->getValue()))
1867 throw "Record `" + getName() + "', field `" + FieldName.str() +
1868 "' does not have a BitsInit initializer!";
1871 /// getValueAsListInit - This method looks up the specified field and returns
1872 /// its value as a ListInit, throwing an exception if the field does not exist
1873 /// or if the value is not the right type.
1875 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1876 const RecordVal *R = getValue(FieldName);
1877 if (R == 0 || R->getValue() == 0)
1878 throw "Record `" + getName() + "' does not have a field named `" +
1879 FieldName.str() + "'!\n";
1881 if (ListInit *LI = dynamic_cast<ListInit*>(R->getValue()))
1883 throw "Record `" + getName() + "', field `" + FieldName.str() +
1884 "' does not have a list initializer!";
1887 /// getValueAsListOfDefs - This method looks up the specified field and returns
1888 /// its value as a vector of records, throwing an exception if the field does
1889 /// not exist or if the value is not the right type.
1891 std::vector<Record*>
1892 Record::getValueAsListOfDefs(StringRef FieldName) const {
1893 ListInit *List = getValueAsListInit(FieldName);
1894 std::vector<Record*> Defs;
1895 for (unsigned i = 0; i < List->getSize(); i++) {
1896 if (DefInit *DI = dynamic_cast<DefInit*>(List->getElement(i))) {
1897 Defs.push_back(DI->getDef());
1899 throw "Record `" + getName() + "', field `" + FieldName.str() +
1900 "' list is not entirely DefInit!";
1906 /// getValueAsInt - This method looks up the specified field and returns its
1907 /// value as an int64_t, throwing an exception if the field does not exist or if
1908 /// the value is not the right type.
1910 int64_t Record::getValueAsInt(StringRef FieldName) const {
1911 const RecordVal *R = getValue(FieldName);
1912 if (R == 0 || R->getValue() == 0)
1913 throw "Record `" + getName() + "' does not have a field named `" +
1914 FieldName.str() + "'!\n";
1916 if (IntInit *II = dynamic_cast<IntInit*>(R->getValue()))
1917 return II->getValue();
1918 throw "Record `" + getName() + "', field `" + FieldName.str() +
1919 "' does not have an int initializer!";
1922 /// getValueAsListOfInts - This method looks up the specified field and returns
1923 /// its value as a vector of integers, throwing an exception if the field does
1924 /// not exist or if the value is not the right type.
1926 std::vector<int64_t>
1927 Record::getValueAsListOfInts(StringRef FieldName) const {
1928 ListInit *List = getValueAsListInit(FieldName);
1929 std::vector<int64_t> Ints;
1930 for (unsigned i = 0; i < List->getSize(); i++) {
1931 if (IntInit *II = dynamic_cast<IntInit*>(List->getElement(i))) {
1932 Ints.push_back(II->getValue());
1934 throw "Record `" + getName() + "', field `" + FieldName.str() +
1935 "' does not have a list of ints initializer!";
1941 /// getValueAsListOfStrings - This method looks up the specified field and
1942 /// returns its value as a vector of strings, throwing an exception if the
1943 /// field does not exist or if the value is not the right type.
1945 std::vector<std::string>
1946 Record::getValueAsListOfStrings(StringRef FieldName) const {
1947 ListInit *List = getValueAsListInit(FieldName);
1948 std::vector<std::string> Strings;
1949 for (unsigned i = 0; i < List->getSize(); i++) {
1950 if (StringInit *II = dynamic_cast<StringInit*>(List->getElement(i))) {
1951 Strings.push_back(II->getValue());
1953 throw "Record `" + getName() + "', field `" + FieldName.str() +
1954 "' does not have a list of strings initializer!";
1960 /// getValueAsDef - This method looks up the specified field and returns its
1961 /// value as a Record, throwing an exception if the field does not exist or if
1962 /// the value is not the right type.
1964 Record *Record::getValueAsDef(StringRef FieldName) const {
1965 const RecordVal *R = getValue(FieldName);
1966 if (R == 0 || R->getValue() == 0)
1967 throw "Record `" + getName() + "' does not have a field named `" +
1968 FieldName.str() + "'!\n";
1970 if (DefInit *DI = dynamic_cast<DefInit*>(R->getValue()))
1971 return DI->getDef();
1972 throw "Record `" + getName() + "', field `" + FieldName.str() +
1973 "' does not have a def initializer!";
1976 /// getValueAsBit - This method looks up the specified field and returns its
1977 /// value as a bit, throwing an exception if the field does not exist or if
1978 /// the value is not the right type.
1980 bool Record::getValueAsBit(StringRef FieldName) const {
1981 const RecordVal *R = getValue(FieldName);
1982 if (R == 0 || R->getValue() == 0)
1983 throw "Record `" + getName() + "' does not have a field named `" +
1984 FieldName.str() + "'!\n";
1986 if (BitInit *BI = dynamic_cast<BitInit*>(R->getValue()))
1987 return BI->getValue();
1988 throw "Record `" + getName() + "', field `" + FieldName.str() +
1989 "' does not have a bit initializer!";
1992 /// getValueAsDag - This method looks up the specified field and returns its
1993 /// value as an Dag, throwing an exception if the field does not exist or if
1994 /// the value is not the right type.
1996 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1997 const RecordVal *R = getValue(FieldName);
1998 if (R == 0 || R->getValue() == 0)
1999 throw "Record `" + getName() + "' does not have a field named `" +
2000 FieldName.str() + "'!\n";
2002 if (DagInit *DI = dynamic_cast<DagInit*>(R->getValue()))
2004 throw "Record `" + getName() + "', field `" + FieldName.str() +
2005 "' does not have a dag initializer!";
2008 std::string Record::getValueAsCode(StringRef FieldName) const {
2009 const RecordVal *R = getValue(FieldName);
2010 if (R == 0 || R->getValue() == 0)
2011 throw "Record `" + getName() + "' does not have a field named `" +
2012 FieldName.str() + "'!\n";
2014 if (CodeInit *CI = dynamic_cast<CodeInit*>(R->getValue()))
2015 return CI->getValue();
2016 throw "Record `" + getName() + "', field `" + FieldName.str() +
2017 "' does not have a code initializer!";
2021 void MultiClass::dump() const {
2022 errs() << "Record:\n";
2025 errs() << "Defs:\n";
2026 for (RecordVector::const_iterator r = DefPrototypes.begin(),
2027 rend = DefPrototypes.end();
2035 void RecordKeeper::dump() const { errs() << *this; }
2037 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
2038 OS << "------------- Classes -----------------\n";
2039 const std::map<std::string, Record*> &Classes = RK.getClasses();
2040 for (std::map<std::string, Record*>::const_iterator I = Classes.begin(),
2041 E = Classes.end(); I != E; ++I)
2042 OS << "class " << *I->second;
2044 OS << "------------- Defs -----------------\n";
2045 const std::map<std::string, Record*> &Defs = RK.getDefs();
2046 for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),
2047 E = Defs.end(); I != E; ++I)
2048 OS << "def " << *I->second;
2053 /// getAllDerivedDefinitions - This method returns all concrete definitions
2054 /// that derive from the specified class name. If a class with the specified
2055 /// name does not exist, an error is printed and true is returned.
2056 std::vector<Record*>
2057 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
2058 Record *Class = getClass(ClassName);
2060 throw "ERROR: Couldn't find the `" + ClassName + "' class!\n";
2062 std::vector<Record*> Defs;
2063 for (std::map<std::string, Record*>::const_iterator I = getDefs().begin(),
2064 E = getDefs().end(); I != E; ++I)
2065 if (I->second->isSubClassOf(Class))
2066 Defs.push_back(I->second);
2071 /// QualifyName - Return an Init with a qualifier prefix referring
2072 /// to CurRec's name.
2073 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2074 Init *Name, const std::string &Scoper) {
2075 RecTy *Type = dynamic_cast<TypedInit *>(Name)->getType();
2077 BinOpInit *NewName =
2078 BinOpInit::get(BinOpInit::STRCONCAT,
2079 BinOpInit::get(BinOpInit::STRCONCAT,
2080 CurRec.getNameInit(),
2081 StringInit::get(Scoper),
2082 Type)->Fold(&CurRec, CurMultiClass),
2086 if (CurMultiClass && Scoper != "::") {
2088 BinOpInit::get(BinOpInit::STRCONCAT,
2089 BinOpInit::get(BinOpInit::STRCONCAT,
2090 CurMultiClass->Rec.getNameInit(),
2091 StringInit::get("::"),
2092 Type)->Fold(&CurRec, CurMultiClass),
2093 NewName->Fold(&CurRec, CurMultiClass),
2097 return NewName->Fold(&CurRec, CurMultiClass);
2100 /// QualifyName - Return an Init with a qualifier prefix referring
2101 /// to CurRec's name.
2102 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2103 const std::string &Name,
2104 const std::string &Scoper) {
2105 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);