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/Hashing.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringMap.h"
29 //===----------------------------------------------------------------------===//
30 // std::string wrapper for DenseMap purposes
31 //===----------------------------------------------------------------------===//
35 /// TableGenStringKey - This is a wrapper for std::string suitable for
36 /// using as a key to a DenseMap. Because there isn't a particularly
37 /// good way to indicate tombstone or empty keys for strings, we want
38 /// to wrap std::string to indicate that this is a "special" string
39 /// not expected to take on certain values (those of the tombstone and
40 /// empty keys). This makes things a little safer as it clarifies
41 /// that DenseMap is really not appropriate for general strings.
43 class TableGenStringKey {
45 TableGenStringKey(const std::string &str) : data(str) {}
46 TableGenStringKey(const char *str) : data(str) {}
48 const std::string &str() const { return data; }
50 friend hash_code hash_value(const TableGenStringKey &Value) {
51 using llvm::hash_value;
52 return hash_value(Value.str());
58 /// Specialize DenseMapInfo for TableGenStringKey.
59 template<> struct DenseMapInfo<TableGenStringKey> {
60 static inline TableGenStringKey getEmptyKey() {
61 TableGenStringKey Empty("<<<EMPTY KEY>>>");
64 static inline TableGenStringKey getTombstoneKey() {
65 TableGenStringKey Tombstone("<<<TOMBSTONE KEY>>>");
68 static unsigned getHashValue(const TableGenStringKey& Val) {
69 using llvm::hash_value;
70 return hash_value(Val);
72 static bool isEqual(const TableGenStringKey& LHS,
73 const TableGenStringKey& RHS) {
74 return LHS.str() == RHS.str();
80 //===----------------------------------------------------------------------===//
81 // Type implementations
82 //===----------------------------------------------------------------------===//
84 BitRecTy BitRecTy::Shared;
85 IntRecTy IntRecTy::Shared;
86 StringRecTy StringRecTy::Shared;
87 DagRecTy DagRecTy::Shared;
89 void RecTy::anchor() { }
90 void RecTy::dump() const { print(errs()); }
92 ListRecTy *RecTy::getListTy() {
94 ListTy = new ListRecTy(this);
98 Init *BitRecTy::convertValue(BitsInit *BI) {
99 if (BI->getNumBits() != 1) return 0; // Only accept if just one bit!
100 return BI->getBit(0);
103 bool BitRecTy::baseClassOf(const BitsRecTy *RHS) const {
104 return RHS->getNumBits() == 1;
107 Init *BitRecTy::convertValue(IntInit *II) {
108 int64_t Val = II->getValue();
109 if (Val != 0 && Val != 1) return 0; // Only accept 0 or 1 for a bit!
111 return BitInit::get(Val != 0);
114 Init *BitRecTy::convertValue(TypedInit *VI) {
115 RecTy *Ty = VI->getType();
116 if (isa<BitRecTy>(Ty) || isa<BitsRecTy>(Ty) || isa<IntRecTy>(Ty))
117 return VI; // Accept variable if it is already of bit type!
121 BitsRecTy *BitsRecTy::get(unsigned Sz) {
122 static std::vector<BitsRecTy*> Shared;
123 if (Sz >= Shared.size())
124 Shared.resize(Sz + 1);
125 BitsRecTy *&Ty = Shared[Sz];
127 Ty = new BitsRecTy(Sz);
131 std::string BitsRecTy::getAsString() const {
132 return "bits<" + utostr(Size) + ">";
135 Init *BitsRecTy::convertValue(UnsetInit *UI) {
136 SmallVector<Init *, 16> NewBits(Size);
138 for (unsigned i = 0; i != Size; ++i)
139 NewBits[i] = UnsetInit::get();
141 return BitsInit::get(NewBits);
144 Init *BitsRecTy::convertValue(BitInit *UI) {
145 if (Size != 1) return 0; // Can only convert single bit.
146 return BitsInit::get(UI);
149 /// canFitInBitfield - Return true if the number of bits is large enough to hold
150 /// the integer value.
151 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
152 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
153 return (NumBits >= sizeof(Value) * 8) ||
154 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
157 /// convertValue from Int initializer to bits type: Split the integer up into the
158 /// appropriate bits.
160 Init *BitsRecTy::convertValue(IntInit *II) {
161 int64_t Value = II->getValue();
162 // Make sure this bitfield is large enough to hold the integer value.
163 if (!canFitInBitfield(Value, Size))
166 SmallVector<Init *, 16> NewBits(Size);
168 for (unsigned i = 0; i != Size; ++i)
169 NewBits[i] = BitInit::get(Value & (1LL << i));
171 return BitsInit::get(NewBits);
174 Init *BitsRecTy::convertValue(BitsInit *BI) {
175 // If the number of bits is right, return it. Otherwise we need to expand or
177 if (BI->getNumBits() == Size) return BI;
181 Init *BitsRecTy::convertValue(TypedInit *VI) {
182 if (Size == 1 && isa<BitRecTy>(VI->getType()))
183 return BitsInit::get(VI);
185 if (VI->getType()->typeIsConvertibleTo(this)) {
186 SmallVector<Init *, 16> NewBits(Size);
188 for (unsigned i = 0; i != Size; ++i)
189 NewBits[i] = VarBitInit::get(VI, i);
190 return BitsInit::get(NewBits);
196 Init *IntRecTy::convertValue(BitInit *BI) {
197 return IntInit::get(BI->getValue());
200 Init *IntRecTy::convertValue(BitsInit *BI) {
202 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
203 if (BitInit *Bit = dyn_cast<BitInit>(BI->getBit(i))) {
204 Result |= Bit->getValue() << i;
208 return IntInit::get(Result);
211 Init *IntRecTy::convertValue(TypedInit *TI) {
212 if (TI->getType()->typeIsConvertibleTo(this))
213 return TI; // Accept variable if already of the right type!
217 Init *StringRecTy::convertValue(UnOpInit *BO) {
218 if (BO->getOpcode() == UnOpInit::CAST) {
219 Init *L = BO->getOperand()->convertInitializerTo(this);
220 if (L == 0) return 0;
221 if (L != BO->getOperand())
222 return UnOpInit::get(UnOpInit::CAST, L, new StringRecTy);
226 return convertValue((TypedInit*)BO);
229 Init *StringRecTy::convertValue(BinOpInit *BO) {
230 if (BO->getOpcode() == BinOpInit::STRCONCAT) {
231 Init *L = BO->getLHS()->convertInitializerTo(this);
232 Init *R = BO->getRHS()->convertInitializerTo(this);
233 if (L == 0 || R == 0) return 0;
234 if (L != BO->getLHS() || R != BO->getRHS())
235 return BinOpInit::get(BinOpInit::STRCONCAT, L, R, new StringRecTy);
239 return convertValue((TypedInit*)BO);
243 Init *StringRecTy::convertValue(TypedInit *TI) {
244 if (isa<StringRecTy>(TI->getType()))
245 return TI; // Accept variable if already of the right type!
249 std::string ListRecTy::getAsString() const {
250 return "list<" + Ty->getAsString() + ">";
253 Init *ListRecTy::convertValue(ListInit *LI) {
254 std::vector<Init*> Elements;
256 // Verify that all of the elements of the list are subclasses of the
257 // appropriate class!
258 for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
259 if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
260 Elements.push_back(CI);
264 if (!isa<ListRecTy>(LI->getType()))
267 return ListInit::get(Elements, this);
270 Init *ListRecTy::convertValue(TypedInit *TI) {
271 // Ensure that TI is compatible with our class.
272 if (ListRecTy *LRT = dyn_cast<ListRecTy>(TI->getType()))
273 if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
278 Init *DagRecTy::convertValue(TypedInit *TI) {
279 if (TI->getType()->typeIsConvertibleTo(this))
284 Init *DagRecTy::convertValue(UnOpInit *BO) {
285 if (BO->getOpcode() == UnOpInit::CAST) {
286 Init *L = BO->getOperand()->convertInitializerTo(this);
287 if (L == 0) return 0;
288 if (L != BO->getOperand())
289 return UnOpInit::get(UnOpInit::CAST, L, new DagRecTy);
295 Init *DagRecTy::convertValue(BinOpInit *BO) {
296 if (BO->getOpcode() == BinOpInit::CONCAT) {
297 Init *L = BO->getLHS()->convertInitializerTo(this);
298 Init *R = BO->getRHS()->convertInitializerTo(this);
299 if (L == 0 || R == 0) return 0;
300 if (L != BO->getLHS() || R != BO->getRHS())
301 return BinOpInit::get(BinOpInit::CONCAT, L, R, new DagRecTy);
307 RecordRecTy *RecordRecTy::get(Record *R) {
308 return dyn_cast<RecordRecTy>(R->getDefInit()->getType());
311 std::string RecordRecTy::getAsString() const {
312 return Rec->getName();
315 Init *RecordRecTy::convertValue(DefInit *DI) {
316 // Ensure that DI is a subclass of Rec.
317 if (!DI->getDef()->isSubClassOf(Rec))
322 Init *RecordRecTy::convertValue(TypedInit *TI) {
323 // Ensure that TI is compatible with Rec.
324 if (RecordRecTy *RRT = dyn_cast<RecordRecTy>(TI->getType()))
325 if (RRT->getRecord()->isSubClassOf(getRecord()) ||
326 RRT->getRecord() == getRecord())
331 bool RecordRecTy::baseClassOf(const RecordRecTy *RHS) const {
332 if (Rec == RHS->getRecord() || RHS->getRecord()->isSubClassOf(Rec))
335 const std::vector<Record*> &SC = Rec->getSuperClasses();
336 for (unsigned i = 0, e = SC.size(); i != e; ++i)
337 if (RHS->getRecord()->isSubClassOf(SC[i]))
343 /// resolveTypes - Find a common type that T1 and T2 convert to.
344 /// Return 0 if no such type exists.
346 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
347 if (T1->typeIsConvertibleTo(T2))
349 if (T2->typeIsConvertibleTo(T1))
352 // If one is a Record type, check superclasses
353 if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
354 // See if T2 inherits from a type T1 also inherits from
355 const std::vector<Record *> &T1SuperClasses =
356 RecTy1->getRecord()->getSuperClasses();
357 for(std::vector<Record *>::const_iterator i = T1SuperClasses.begin(),
358 iend = T1SuperClasses.end();
361 RecordRecTy *SuperRecTy1 = RecordRecTy::get(*i);
362 RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
364 if (NewType1 != SuperRecTy1) {
371 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) {
372 // See if T1 inherits from a type T2 also inherits from
373 const std::vector<Record *> &T2SuperClasses =
374 RecTy2->getRecord()->getSuperClasses();
375 for (std::vector<Record *>::const_iterator i = T2SuperClasses.begin(),
376 iend = T2SuperClasses.end();
379 RecordRecTy *SuperRecTy2 = RecordRecTy::get(*i);
380 RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
382 if (NewType2 != SuperRecTy2) {
393 //===----------------------------------------------------------------------===//
394 // Initializer implementations
395 //===----------------------------------------------------------------------===//
397 void Init::anchor() { }
398 void Init::dump() const { return print(errs()); }
400 void UnsetInit::anchor() { }
402 UnsetInit *UnsetInit::get() {
403 static UnsetInit TheInit;
407 void BitInit::anchor() { }
409 BitInit *BitInit::get(bool V) {
410 static BitInit True(true);
411 static BitInit False(false);
413 return V ? &True : &False;
417 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
418 ID.AddInteger(Range.size());
420 for (ArrayRef<Init *>::iterator i = Range.begin(),
427 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
428 typedef FoldingSet<BitsInit> Pool;
432 ProfileBitsInit(ID, Range);
435 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
438 BitsInit *I = new BitsInit(Range);
439 ThePool.InsertNode(I, IP);
444 void BitsInit::Profile(FoldingSetNodeID &ID) const {
445 ProfileBitsInit(ID, Bits);
449 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
450 SmallVector<Init *, 16> NewBits(Bits.size());
452 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
453 if (Bits[i] >= getNumBits())
455 NewBits[i] = getBit(Bits[i]);
457 return BitsInit::get(NewBits);
460 std::string BitsInit::getAsString() const {
461 std::string Result = "{ ";
462 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
463 if (i) Result += ", ";
464 if (Init *Bit = getBit(e-i-1))
465 Result += Bit->getAsString();
469 return Result + " }";
472 // Fix bit initializer to preserve the behavior that bit reference from a unset
473 // bits initializer will resolve into VarBitInit to keep the field name and bit
474 // number used in targets with fixed insn length.
475 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
476 if (RV || After != UnsetInit::get())
481 // resolveReferences - If there are any field references that refer to fields
482 // that have been filled in, we can propagate the values now.
484 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
485 bool Changed = false;
486 SmallVector<Init *, 16> NewBits(getNumBits());
488 Init *CachedInit = 0;
489 Init *CachedBitVar = 0;
490 bool CachedBitVarChanged = false;
492 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
493 Init *CurBit = Bits[i];
494 Init *CurBitVar = CurBit->getBitVar();
498 if (CurBitVar == CachedBitVar) {
499 if (CachedBitVarChanged) {
500 Init *Bit = CachedInit->getBit(CurBit->getBitNum());
501 NewBits[i] = fixBitInit(RV, CurBit, Bit);
505 CachedBitVar = CurBitVar;
506 CachedBitVarChanged = false;
511 CurBitVar = CurBitVar->resolveReferences(R, RV);
512 CachedBitVarChanged |= B != CurBitVar;
513 Changed |= B != CurBitVar;
514 } while (B != CurBitVar);
515 CachedInit = CurBitVar;
517 if (CachedBitVarChanged) {
518 Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
519 NewBits[i] = fixBitInit(RV, CurBit, Bit);
524 return BitsInit::get(NewBits);
526 return const_cast<BitsInit *>(this);
529 IntInit *IntInit::get(int64_t V) {
530 typedef DenseMap<int64_t, IntInit *> Pool;
533 IntInit *&I = ThePool[V];
534 if (!I) I = new IntInit(V);
538 std::string IntInit::getAsString() const {
539 return itostr(Value);
543 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
544 SmallVector<Init *, 16> NewBits(Bits.size());
546 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
550 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
552 return BitsInit::get(NewBits);
555 void StringInit::anchor() { }
557 StringInit *StringInit::get(StringRef V) {
558 typedef StringMap<StringInit *> Pool;
561 StringInit *&I = ThePool[V];
562 if (!I) I = new StringInit(V);
566 static void ProfileListInit(FoldingSetNodeID &ID,
567 ArrayRef<Init *> Range,
569 ID.AddInteger(Range.size());
570 ID.AddPointer(EltTy);
572 for (ArrayRef<Init *>::iterator i = Range.begin(),
579 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
580 typedef FoldingSet<ListInit> Pool;
583 // Just use the FoldingSetNodeID to compute a hash. Use a DenseMap
584 // for actual storage.
586 ProfileListInit(ID, Range, EltTy);
589 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
592 ListInit *I = new ListInit(Range, EltTy);
593 ThePool.InsertNode(I, IP);
597 void ListInit::Profile(FoldingSetNodeID &ID) const {
598 ListRecTy *ListType = dyn_cast<ListRecTy>(getType());
599 assert(ListType && "Bad type for ListInit!");
600 RecTy *EltTy = ListType->getElementType();
602 ProfileListInit(ID, Values, EltTy);
606 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
607 std::vector<Init*> Vals;
608 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
609 if (Elements[i] >= getSize())
611 Vals.push_back(getElement(Elements[i]));
613 return ListInit::get(Vals, getType());
616 Record *ListInit::getElementAsRecord(unsigned i) const {
617 assert(i < Values.size() && "List element index out of range!");
618 DefInit *DI = dyn_cast<DefInit>(Values[i]);
619 if (DI == 0) throw "Expected record in list!";
623 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
624 std::vector<Init*> Resolved;
625 Resolved.reserve(getSize());
626 bool Changed = false;
628 for (unsigned i = 0, e = getSize(); i != e; ++i) {
630 Init *CurElt = getElement(i);
634 CurElt = CurElt->resolveReferences(R, RV);
635 Changed |= E != CurElt;
636 } while (E != CurElt);
637 Resolved.push_back(E);
641 return ListInit::get(Resolved, getType());
642 return const_cast<ListInit *>(this);
645 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
646 unsigned Elt) const {
647 if (Elt >= getSize())
648 return 0; // Out of range reference.
649 Init *E = getElement(Elt);
650 // If the element is set to some value, or if we are resolving a reference
651 // to a specific variable and that variable is explicitly unset, then
652 // replace the VarListElementInit with it.
653 if (IRV || !isa<UnsetInit>(E))
658 std::string ListInit::getAsString() const {
659 std::string Result = "[";
660 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
661 if (i) Result += ", ";
662 Result += Values[i]->getAsString();
667 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
668 unsigned Elt) const {
669 Init *Resolved = resolveReferences(R, IRV);
670 OpInit *OResolved = dyn_cast<OpInit>(Resolved);
672 Resolved = OResolved->Fold(&R, 0);
675 if (Resolved != this) {
676 TypedInit *Typed = dyn_cast<TypedInit>(Resolved);
677 assert(Typed && "Expected typed init for list reference");
679 Init *New = Typed->resolveListElementReference(R, IRV, Elt);
682 return VarListElementInit::get(Typed, Elt);
689 Init *OpInit::getBit(unsigned Bit) const {
690 if (getType() == BitRecTy::get())
691 return const_cast<OpInit*>(this);
692 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
695 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
696 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
698 typedef DenseMap<Key, UnOpInit *> Pool;
701 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
703 UnOpInit *&I = ThePool[TheKey];
704 if (!I) I = new UnOpInit(opc, lhs, Type);
708 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
709 switch (getOpcode()) {
711 if (getType()->getAsString() == "string") {
712 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
715 if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
716 return StringInit::get(LHSd->getDef()->getName());
718 if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
719 return StringInit::get(LHSi->getAsString());
721 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
722 std::string Name = LHSs->getValue();
724 // From TGParser::ParseIDValue
726 if (const RecordVal *RV = CurRec->getValue(Name)) {
727 if (RV->getType() != getType())
728 throw "type mismatch in cast";
729 return VarInit::get(Name, RV->getType());
732 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
735 if (CurRec->isTemplateArg(TemplateArgName)) {
736 const RecordVal *RV = CurRec->getValue(TemplateArgName);
737 assert(RV && "Template arg doesn't exist??");
739 if (RV->getType() != getType())
740 throw "type mismatch in cast";
742 return VarInit::get(TemplateArgName, RV->getType());
747 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
749 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
750 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
751 assert(RV && "Template arg doesn't exist??");
753 if (RV->getType() != getType())
754 throw "type mismatch in cast";
756 return VarInit::get(MCName, RV->getType());
760 if (Record *D = (CurRec->getRecords()).getDef(Name))
761 return DefInit::get(D);
763 throw TGError(CurRec->getLoc(), "Undefined reference:'" + Name + "'\n");
769 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
770 if (LHSl->getSize() == 0) {
771 assert(0 && "Empty list in car");
774 return LHSl->getElement(0);
779 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
780 if (LHSl->getSize() == 0) {
781 assert(0 && "Empty list in cdr");
784 // Note the +1. We can't just pass the result of getValues()
786 ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
787 ArrayRef<Init *>::iterator end = LHSl->getValues().end();
789 ListInit::get(ArrayRef<Init *>(begin, end - begin),
796 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
797 if (LHSl->getSize() == 0) {
798 return IntInit::get(1);
800 return IntInit::get(0);
803 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
804 if (LHSs->getValue().empty()) {
805 return IntInit::get(1);
807 return IntInit::get(0);
814 return const_cast<UnOpInit *>(this);
817 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
818 Init *lhs = LHS->resolveReferences(R, RV);
821 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, 0);
825 std::string UnOpInit::getAsString() const {
828 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
829 case HEAD: Result = "!head"; break;
830 case TAIL: Result = "!tail"; break;
831 case EMPTY: Result = "!empty"; break;
833 return Result + "(" + LHS->getAsString() + ")";
836 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
837 Init *rhs, RecTy *Type) {
839 std::pair<std::pair<unsigned, Init *>, Init *>,
843 typedef DenseMap<Key, BinOpInit *> Pool;
846 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
849 BinOpInit *&I = ThePool[TheKey];
850 if (!I) I = new BinOpInit(opc, lhs, rhs, Type);
854 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
855 switch (getOpcode()) {
857 DagInit *LHSs = dyn_cast<DagInit>(LHS);
858 DagInit *RHSs = dyn_cast<DagInit>(RHS);
860 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
861 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
862 if (LOp == 0 || ROp == 0 || LOp->getDef() != ROp->getDef())
863 throw "Concated Dag operators do not match!";
864 std::vector<Init*> Args;
865 std::vector<std::string> ArgNames;
866 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
867 Args.push_back(LHSs->getArg(i));
868 ArgNames.push_back(LHSs->getArgName(i));
870 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
871 Args.push_back(RHSs->getArg(i));
872 ArgNames.push_back(RHSs->getArgName(i));
874 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
879 StringInit *LHSs = dyn_cast<StringInit>(LHS);
880 StringInit *RHSs = dyn_cast<StringInit>(RHS);
882 return StringInit::get(LHSs->getValue() + RHSs->getValue());
886 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
887 // to string objects.
889 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
891 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
894 return IntInit::get(L->getValue() == R->getValue());
896 StringInit *LHSs = dyn_cast<StringInit>(LHS);
897 StringInit *RHSs = dyn_cast<StringInit>(RHS);
899 // Make sure we've resolved
901 return IntInit::get(LHSs->getValue() == RHSs->getValue());
908 IntInit *LHSi = dyn_cast<IntInit>(LHS);
909 IntInit *RHSi = dyn_cast<IntInit>(RHS);
911 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
913 switch (getOpcode()) {
914 default: llvm_unreachable("Bad opcode!");
915 case SHL: Result = LHSv << RHSv; break;
916 case SRA: Result = LHSv >> RHSv; break;
917 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
919 return IntInit::get(Result);
924 return const_cast<BinOpInit *>(this);
927 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
928 Init *lhs = LHS->resolveReferences(R, RV);
929 Init *rhs = RHS->resolveReferences(R, RV);
931 if (LHS != lhs || RHS != rhs)
932 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R, 0);
936 std::string BinOpInit::getAsString() const {
939 case CONCAT: Result = "!con"; break;
940 case SHL: Result = "!shl"; break;
941 case SRA: Result = "!sra"; break;
942 case SRL: Result = "!srl"; break;
943 case EQ: Result = "!eq"; break;
944 case STRCONCAT: Result = "!strconcat"; break;
946 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
949 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs,
950 Init *mhs, Init *rhs,
954 std::pair<std::pair<unsigned, RecTy *>, Init *>,
960 typedef DenseMap<Key, TernOpInit *> Pool;
963 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
969 TernOpInit *&I = ThePool[TheKey];
970 if (!I) I = new TernOpInit(opc, lhs, mhs, rhs, Type);
974 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
975 Record *CurRec, MultiClass *CurMultiClass);
977 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
978 RecTy *Type, Record *CurRec,
979 MultiClass *CurMultiClass) {
980 std::vector<Init *> NewOperands;
982 TypedInit *TArg = dyn_cast<TypedInit>(Arg);
984 // If this is a dag, recurse
985 if (TArg && TArg->getType()->getAsString() == "dag") {
986 Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
987 CurRec, CurMultiClass);
995 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
996 OpInit *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i));
999 Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1000 Type, CurRec, CurMultiClass);
1002 NewOperands.push_back(Result);
1004 NewOperands.push_back(Arg);
1006 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1007 NewOperands.push_back(Arg);
1009 NewOperands.push_back(RHSo->getOperand(i));
1013 // Now run the operator and use its result as the new leaf
1014 const OpInit *NewOp = RHSo->clone(NewOperands);
1015 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
1016 if (NewVal != NewOp)
1022 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1023 Record *CurRec, MultiClass *CurMultiClass) {
1024 DagInit *MHSd = dyn_cast<DagInit>(MHS);
1025 ListInit *MHSl = dyn_cast<ListInit>(MHS);
1027 OpInit *RHSo = dyn_cast<OpInit>(RHS);
1030 throw TGError(CurRec->getLoc(), "!foreach requires an operator\n");
1033 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1036 throw TGError(CurRec->getLoc(), "!foreach requires typed variable\n");
1039 if ((MHSd && isa<DagRecTy>(Type)) || (MHSl && isa<ListRecTy>(Type))) {
1041 Init *Val = MHSd->getOperator();
1042 Init *Result = EvaluateOperation(RHSo, LHS, Val,
1043 Type, CurRec, CurMultiClass);
1048 std::vector<std::pair<Init *, std::string> > args;
1049 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1051 std::string ArgName;
1052 Arg = MHSd->getArg(i);
1053 ArgName = MHSd->getArgName(i);
1056 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1057 CurRec, CurMultiClass);
1062 // TODO: Process arg names
1063 args.push_back(std::make_pair(Arg, ArgName));
1066 return DagInit::get(Val, "", args);
1069 std::vector<Init *> NewOperands;
1070 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1072 for (std::vector<Init *>::iterator li = NewList.begin(),
1073 liend = NewList.end();
1077 NewOperands.clear();
1078 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1079 // First, replace the foreach variable with the list item
1080 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1081 NewOperands.push_back(Item);
1083 NewOperands.push_back(RHSo->getOperand(i));
1087 // Now run the operator and use its result as the new list item
1088 const OpInit *NewOp = RHSo->clone(NewOperands);
1089 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1090 if (NewItem != NewOp)
1093 return ListInit::get(NewList, MHSl->getType());
1099 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1100 switch (getOpcode()) {
1102 DefInit *LHSd = dyn_cast<DefInit>(LHS);
1103 VarInit *LHSv = dyn_cast<VarInit>(LHS);
1104 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1106 DefInit *MHSd = dyn_cast<DefInit>(MHS);
1107 VarInit *MHSv = dyn_cast<VarInit>(MHS);
1108 StringInit *MHSs = dyn_cast<StringInit>(MHS);
1110 DefInit *RHSd = dyn_cast<DefInit>(RHS);
1111 VarInit *RHSv = dyn_cast<VarInit>(RHS);
1112 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1114 if ((LHSd && MHSd && RHSd)
1115 || (LHSv && MHSv && RHSv)
1116 || (LHSs && MHSs && RHSs)) {
1118 Record *Val = RHSd->getDef();
1119 if (LHSd->getAsString() == RHSd->getAsString()) {
1120 Val = MHSd->getDef();
1122 return DefInit::get(Val);
1125 std::string Val = RHSv->getName();
1126 if (LHSv->getAsString() == RHSv->getAsString()) {
1127 Val = MHSv->getName();
1129 return VarInit::get(Val, getType());
1132 std::string Val = RHSs->getValue();
1134 std::string::size_type found;
1135 std::string::size_type idx = 0;
1137 found = Val.find(LHSs->getValue(), idx);
1138 if (found != std::string::npos) {
1139 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1141 idx = found + MHSs->getValue().size();
1142 } while (found != std::string::npos);
1144 return StringInit::get(Val);
1151 Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1152 CurRec, CurMultiClass);
1160 IntInit *LHSi = dyn_cast<IntInit>(LHS);
1161 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1162 LHSi = dyn_cast<IntInit>(I);
1164 if (LHSi->getValue()) {
1174 return const_cast<TernOpInit *>(this);
1177 Init *TernOpInit::resolveReferences(Record &R,
1178 const RecordVal *RV) const {
1179 Init *lhs = LHS->resolveReferences(R, RV);
1181 if (Opc == IF && lhs != LHS) {
1182 IntInit *Value = dyn_cast<IntInit>(lhs);
1183 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1184 Value = dyn_cast<IntInit>(I);
1187 if (Value->getValue()) {
1188 Init *mhs = MHS->resolveReferences(R, RV);
1189 return (TernOpInit::get(getOpcode(), lhs, mhs,
1190 RHS, getType()))->Fold(&R, 0);
1192 Init *rhs = RHS->resolveReferences(R, RV);
1193 return (TernOpInit::get(getOpcode(), lhs, MHS,
1194 rhs, getType()))->Fold(&R, 0);
1199 Init *mhs = MHS->resolveReferences(R, RV);
1200 Init *rhs = RHS->resolveReferences(R, RV);
1202 if (LHS != lhs || MHS != mhs || RHS != rhs)
1203 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1204 getType()))->Fold(&R, 0);
1208 std::string TernOpInit::getAsString() const {
1211 case SUBST: Result = "!subst"; break;
1212 case FOREACH: Result = "!foreach"; break;
1213 case IF: Result = "!if"; break;
1215 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
1216 + RHS->getAsString() + ")";
1219 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1220 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
1221 if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
1222 return Field->getType();
1227 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1228 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1229 if (T == 0) return 0; // Cannot subscript a non-bits variable.
1230 unsigned NumBits = T->getNumBits();
1232 SmallVector<Init *, 16> NewBits(Bits.size());
1233 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1234 if (Bits[i] >= NumBits)
1237 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1239 return BitsInit::get(NewBits);
1243 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1244 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1245 if (T == 0) return 0; // Cannot subscript a non-list variable.
1247 if (Elements.size() == 1)
1248 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1250 std::vector<Init*> ListInits;
1251 ListInits.reserve(Elements.size());
1252 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1253 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1255 return ListInit::get(ListInits, T);
1259 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1260 Init *Value = StringInit::get(VN);
1261 return VarInit::get(Value, T);
1264 VarInit *VarInit::get(Init *VN, RecTy *T) {
1265 typedef std::pair<RecTy *, Init *> Key;
1266 typedef DenseMap<Key, VarInit *> Pool;
1267 static Pool ThePool;
1269 Key TheKey(std::make_pair(T, VN));
1271 VarInit *&I = ThePool[TheKey];
1272 if (!I) I = new VarInit(VN, T);
1276 const std::string &VarInit::getName() const {
1277 StringInit *NameString = dyn_cast<StringInit>(getNameInit());
1278 assert(NameString && "VarInit name is not a string!");
1279 return NameString->getValue();
1282 Init *VarInit::getBit(unsigned Bit) const {
1283 if (getType() == BitRecTy::get())
1284 return const_cast<VarInit*>(this);
1285 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1288 Init *VarInit::resolveListElementReference(Record &R,
1289 const RecordVal *IRV,
1290 unsigned Elt) const {
1291 if (R.isTemplateArg(getNameInit())) return 0;
1292 if (IRV && IRV->getNameInit() != getNameInit()) return 0;
1294 RecordVal *RV = R.getValue(getNameInit());
1295 assert(RV && "Reference to a non-existent variable?");
1296 ListInit *LI = dyn_cast<ListInit>(RV->getValue());
1298 TypedInit *VI = dyn_cast<TypedInit>(RV->getValue());
1299 assert(VI && "Invalid list element!");
1300 return VarListElementInit::get(VI, Elt);
1303 if (Elt >= LI->getSize())
1304 return 0; // Out of range reference.
1305 Init *E = LI->getElement(Elt);
1306 // If the element is set to some value, or if we are resolving a reference
1307 // to a specific variable and that variable is explicitly unset, then
1308 // replace the VarListElementInit with it.
1309 if (IRV || !isa<UnsetInit>(E))
1315 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1316 if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
1317 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1318 return RV->getType();
1322 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1323 const std::string &FieldName) const {
1324 if (isa<RecordRecTy>(getType()))
1325 if (const RecordVal *Val = R.getValue(VarName)) {
1326 if (RV != Val && (RV || isa<UnsetInit>(Val->getValue())))
1328 Init *TheInit = Val->getValue();
1329 assert(TheInit != this && "Infinite loop detected!");
1330 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1338 /// resolveReferences - This method is used by classes that refer to other
1339 /// variables which may not be defined at the time the expression is formed.
1340 /// If a value is set for the variable later, this method will be called on
1341 /// users of the value to allow the value to propagate out.
1343 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1344 if (RecordVal *Val = R.getValue(VarName))
1345 if (RV == Val || (RV == 0 && !isa<UnsetInit>(Val->getValue())))
1346 return Val->getValue();
1347 return const_cast<VarInit *>(this);
1350 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1351 typedef std::pair<TypedInit *, unsigned> Key;
1352 typedef DenseMap<Key, VarBitInit *> Pool;
1354 static Pool ThePool;
1356 Key TheKey(std::make_pair(T, B));
1358 VarBitInit *&I = ThePool[TheKey];
1359 if (!I) I = new VarBitInit(T, B);
1363 std::string VarBitInit::getAsString() const {
1364 return TI->getAsString() + "{" + utostr(Bit) + "}";
1367 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1368 Init *I = TI->resolveReferences(R, RV);
1370 return I->getBit(getBitNum());
1372 return const_cast<VarBitInit*>(this);
1375 VarListElementInit *VarListElementInit::get(TypedInit *T,
1377 typedef std::pair<TypedInit *, unsigned> Key;
1378 typedef DenseMap<Key, VarListElementInit *> Pool;
1380 static Pool ThePool;
1382 Key TheKey(std::make_pair(T, E));
1384 VarListElementInit *&I = ThePool[TheKey];
1385 if (!I) I = new VarListElementInit(T, E);
1389 std::string VarListElementInit::getAsString() const {
1390 return TI->getAsString() + "[" + utostr(Element) + "]";
1394 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1395 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1398 return const_cast<VarListElementInit *>(this);
1401 Init *VarListElementInit::getBit(unsigned Bit) const {
1402 if (getType() == BitRecTy::get())
1403 return const_cast<VarListElementInit*>(this);
1404 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1407 Init *VarListElementInit:: resolveListElementReference(Record &R,
1408 const RecordVal *RV,
1409 unsigned Elt) const {
1410 Init *Result = TI->resolveListElementReference(R, RV, Element);
1413 if (TypedInit *TInit = dyn_cast<TypedInit>(Result)) {
1414 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1415 if (Result2) return Result2;
1416 return new VarListElementInit(TInit, Elt);
1424 DefInit *DefInit::get(Record *R) {
1425 return R->getDefInit();
1428 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1429 if (const RecordVal *RV = Def->getValue(FieldName))
1430 return RV->getType();
1434 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1435 const std::string &FieldName) const {
1436 return Def->getValue(FieldName)->getValue();
1440 std::string DefInit::getAsString() const {
1441 return Def->getName();
1444 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1445 typedef std::pair<Init *, TableGenStringKey> Key;
1446 typedef DenseMap<Key, FieldInit *> Pool;
1447 static Pool ThePool;
1449 Key TheKey(std::make_pair(R, FN));
1451 FieldInit *&I = ThePool[TheKey];
1452 if (!I) I = new FieldInit(R, FN);
1456 Init *FieldInit::getBit(unsigned Bit) const {
1457 if (getType() == BitRecTy::get())
1458 return const_cast<FieldInit*>(this);
1459 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1462 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1463 unsigned Elt) const {
1464 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1465 if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
1466 if (Elt >= LI->getSize()) return 0;
1467 Init *E = LI->getElement(Elt);
1469 // If the element is set to some value, or if we are resolving a
1470 // reference to a specific variable and that variable is explicitly
1471 // unset, then replace the VarListElementInit with it.
1472 if (RV || !isa<UnsetInit>(E))
1478 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1479 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1481 Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1483 Init *BVR = BitsVal->resolveReferences(R, RV);
1484 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1487 if (NewRec != Rec) {
1488 return FieldInit::get(NewRec, FieldName);
1490 return const_cast<FieldInit *>(this);
1493 void ProfileDagInit(FoldingSetNodeID &ID,
1495 const std::string &VN,
1496 ArrayRef<Init *> ArgRange,
1497 ArrayRef<std::string> NameRange) {
1501 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1502 ArrayRef<std::string>::iterator Name = NameRange.begin();
1503 while (Arg != ArgRange.end()) {
1504 assert(Name != NameRange.end() && "Arg name underflow!");
1505 ID.AddPointer(*Arg++);
1506 ID.AddString(*Name++);
1508 assert(Name == NameRange.end() && "Arg name overflow!");
1512 DagInit::get(Init *V, const std::string &VN,
1513 ArrayRef<Init *> ArgRange,
1514 ArrayRef<std::string> NameRange) {
1515 typedef FoldingSet<DagInit> Pool;
1516 static Pool ThePool;
1518 FoldingSetNodeID ID;
1519 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1522 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1525 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1526 ThePool.InsertNode(I, IP);
1532 DagInit::get(Init *V, const std::string &VN,
1533 const std::vector<std::pair<Init*, std::string> > &args) {
1534 typedef std::pair<Init*, std::string> PairType;
1536 std::vector<Init *> Args;
1537 std::vector<std::string> Names;
1539 for (std::vector<PairType>::const_iterator i = args.begin(),
1543 Args.push_back(i->first);
1544 Names.push_back(i->second);
1547 return DagInit::get(V, VN, Args, Names);
1550 void DagInit::Profile(FoldingSetNodeID &ID) const {
1551 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1554 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1555 std::vector<Init*> NewArgs;
1556 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1557 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1559 Init *Op = Val->resolveReferences(R, RV);
1561 if (Args != NewArgs || Op != Val)
1562 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1564 return const_cast<DagInit *>(this);
1568 std::string DagInit::getAsString() const {
1569 std::string Result = "(" + Val->getAsString();
1570 if (!ValName.empty())
1571 Result += ":" + ValName;
1573 Result += " " + Args[0]->getAsString();
1574 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1575 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1576 Result += ", " + Args[i]->getAsString();
1577 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1580 return Result + ")";
1584 //===----------------------------------------------------------------------===//
1585 // Other implementations
1586 //===----------------------------------------------------------------------===//
1588 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1589 : Name(N), Ty(T), Prefix(P) {
1590 Value = Ty->convertValue(UnsetInit::get());
1591 assert(Value && "Cannot create unset value for current type!");
1594 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1595 : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1596 Value = Ty->convertValue(UnsetInit::get());
1597 assert(Value && "Cannot create unset value for current type!");
1600 const std::string &RecordVal::getName() const {
1601 StringInit *NameString = dyn_cast<StringInit>(Name);
1602 assert(NameString && "RecordVal name is not a string!");
1603 return NameString->getValue();
1606 void RecordVal::dump() const { errs() << *this; }
1608 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1609 if (getPrefix()) OS << "field ";
1610 OS << *getType() << " " << getNameInitAsString();
1613 OS << " = " << *getValue();
1615 if (PrintSem) OS << ";\n";
1618 unsigned Record::LastID = 0;
1620 void Record::init() {
1623 // Every record potentially has a def at the top. This value is
1624 // replaced with the top-level def name at instantiation time.
1625 RecordVal DN("NAME", StringRecTy::get(), 0);
1629 void Record::checkName() {
1630 // Ensure the record name has string type.
1631 const TypedInit *TypedName = dyn_cast<const TypedInit>(Name);
1632 assert(TypedName && "Record name is not typed!");
1633 RecTy *Type = TypedName->getType();
1634 if (!isa<StringRecTy>(Type))
1635 throw TGError(getLoc(), "Record name is not a string!");
1638 DefInit *Record::getDefInit() {
1640 TheInit = new DefInit(this, new RecordRecTy(this));
1644 const std::string &Record::getName() const {
1645 const StringInit *NameString = dyn_cast<StringInit>(Name);
1646 assert(NameString && "Record name is not a string!");
1647 return NameString->getValue();
1650 void Record::setName(Init *NewName) {
1651 if (TrackedRecords.getDef(Name->getAsUnquotedString()) == this) {
1652 TrackedRecords.removeDef(Name->getAsUnquotedString());
1653 TrackedRecords.addDef(this);
1654 } else if (TrackedRecords.getClass(Name->getAsUnquotedString()) == this) {
1655 TrackedRecords.removeClass(Name->getAsUnquotedString());
1656 TrackedRecords.addClass(this);
1657 } // Otherwise this isn't yet registered.
1660 // DO NOT resolve record values to the name at this point because
1661 // there might be default values for arguments of this def. Those
1662 // arguments might not have been resolved yet so we don't want to
1663 // prematurely assume values for those arguments were not passed to
1666 // Nonetheless, it may be that some of this Record's values
1667 // reference the record name. Indeed, the reason for having the
1668 // record name be an Init is to provide this flexibility. The extra
1669 // resolve steps after completely instantiating defs takes care of
1670 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1673 void Record::setName(const std::string &Name) {
1674 setName(StringInit::get(Name));
1677 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1678 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1680 void Record::resolveReferencesTo(const RecordVal *RV) {
1681 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1682 if (RV == &Values[i]) // Skip resolve the same field as the given one
1684 if (Init *V = Values[i].getValue())
1685 if (Values[i].setValue(V->resolveReferences(*this, RV)))
1686 throw TGError(getLoc(), "Invalid value is found when setting '"
1687 + Values[i].getNameInitAsString()
1688 + "' after resolving references"
1689 + (RV ? " against '" + RV->getNameInitAsString()
1691 + RV->getValue()->getAsUnquotedString() + ")"
1695 Init *OldName = getNameInit();
1696 Init *NewName = Name->resolveReferences(*this, RV);
1697 if (NewName != OldName) {
1698 // Re-register with RecordKeeper.
1703 void Record::dump() const { errs() << *this; }
1705 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1706 OS << R.getNameInitAsString();
1708 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1709 if (!TArgs.empty()) {
1711 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1713 const RecordVal *RV = R.getValue(TArgs[i]);
1714 assert(RV && "Template argument record not found??");
1715 RV->print(OS, false);
1721 const std::vector<Record*> &SC = R.getSuperClasses();
1724 for (unsigned i = 0, e = SC.size(); i != e; ++i)
1725 OS << " " << SC[i]->getNameInitAsString();
1729 const std::vector<RecordVal> &Vals = R.getValues();
1730 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1731 if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1733 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1734 if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1740 /// getValueInit - Return the initializer for a value with the specified name,
1741 /// or throw an exception if the field does not exist.
1743 Init *Record::getValueInit(StringRef FieldName) const {
1744 const RecordVal *R = getValue(FieldName);
1745 if (R == 0 || R->getValue() == 0)
1746 throw "Record `" + getName() + "' does not have a field named `" +
1747 FieldName.str() + "'!\n";
1748 return R->getValue();
1752 /// getValueAsString - This method looks up the specified field and returns its
1753 /// value as a string, throwing an exception if the field does not exist or if
1754 /// the value is not a string.
1756 std::string Record::getValueAsString(StringRef FieldName) const {
1757 const RecordVal *R = getValue(FieldName);
1758 if (R == 0 || R->getValue() == 0)
1759 throw "Record `" + getName() + "' does not have a field named `" +
1760 FieldName.str() + "'!\n";
1762 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1763 return SI->getValue();
1764 throw "Record `" + getName() + "', field `" + FieldName.str() +
1765 "' does not have a string initializer!";
1768 /// getValueAsBitsInit - This method looks up the specified field and returns
1769 /// its value as a BitsInit, throwing an exception if the field does not exist
1770 /// or if the value is not the right type.
1772 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1773 const RecordVal *R = getValue(FieldName);
1774 if (R == 0 || R->getValue() == 0)
1775 throw "Record `" + getName() + "' does not have a field named `" +
1776 FieldName.str() + "'!\n";
1778 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
1780 throw "Record `" + getName() + "', field `" + FieldName.str() +
1781 "' does not have a BitsInit initializer!";
1784 /// getValueAsListInit - This method looks up the specified field and returns
1785 /// its value as a ListInit, throwing an exception if the field does not exist
1786 /// or if the value is not the right type.
1788 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1789 const RecordVal *R = getValue(FieldName);
1790 if (R == 0 || R->getValue() == 0)
1791 throw "Record `" + getName() + "' does not have a field named `" +
1792 FieldName.str() + "'!\n";
1794 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
1796 throw "Record `" + getName() + "', field `" + FieldName.str() +
1797 "' does not have a list initializer!";
1800 /// getValueAsListOfDefs - This method looks up the specified field and returns
1801 /// its value as a vector of records, throwing an exception if the field does
1802 /// not exist or if the value is not the right type.
1804 std::vector<Record*>
1805 Record::getValueAsListOfDefs(StringRef FieldName) const {
1806 ListInit *List = getValueAsListInit(FieldName);
1807 std::vector<Record*> Defs;
1808 for (unsigned i = 0; i < List->getSize(); i++) {
1809 if (DefInit *DI = dyn_cast<DefInit>(List->getElement(i))) {
1810 Defs.push_back(DI->getDef());
1812 throw "Record `" + getName() + "', field `" + FieldName.str() +
1813 "' list is not entirely DefInit!";
1819 /// getValueAsInt - This method looks up the specified field and returns its
1820 /// value as an int64_t, throwing an exception if the field does not exist or if
1821 /// the value is not the right type.
1823 int64_t Record::getValueAsInt(StringRef FieldName) const {
1824 const RecordVal *R = getValue(FieldName);
1825 if (R == 0 || R->getValue() == 0)
1826 throw "Record `" + getName() + "' does not have a field named `" +
1827 FieldName.str() + "'!\n";
1829 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
1830 return II->getValue();
1831 throw "Record `" + getName() + "', field `" + FieldName.str() +
1832 "' does not have an int initializer!";
1835 /// getValueAsListOfInts - This method looks up the specified field and returns
1836 /// its value as a vector of integers, throwing an exception if the field does
1837 /// not exist or if the value is not the right type.
1839 std::vector<int64_t>
1840 Record::getValueAsListOfInts(StringRef FieldName) const {
1841 ListInit *List = getValueAsListInit(FieldName);
1842 std::vector<int64_t> Ints;
1843 for (unsigned i = 0; i < List->getSize(); i++) {
1844 if (IntInit *II = dyn_cast<IntInit>(List->getElement(i))) {
1845 Ints.push_back(II->getValue());
1847 throw "Record `" + getName() + "', field `" + FieldName.str() +
1848 "' does not have a list of ints initializer!";
1854 /// getValueAsListOfStrings - This method looks up the specified field and
1855 /// returns its value as a vector of strings, throwing an exception if the
1856 /// field does not exist or if the value is not the right type.
1858 std::vector<std::string>
1859 Record::getValueAsListOfStrings(StringRef FieldName) const {
1860 ListInit *List = getValueAsListInit(FieldName);
1861 std::vector<std::string> Strings;
1862 for (unsigned i = 0; i < List->getSize(); i++) {
1863 if (StringInit *II = dyn_cast<StringInit>(List->getElement(i))) {
1864 Strings.push_back(II->getValue());
1866 throw "Record `" + getName() + "', field `" + FieldName.str() +
1867 "' does not have a list of strings initializer!";
1873 /// getValueAsDef - This method looks up the specified field and returns its
1874 /// value as a Record, throwing an exception if the field does not exist or if
1875 /// the value is not the right type.
1877 Record *Record::getValueAsDef(StringRef FieldName) const {
1878 const RecordVal *R = getValue(FieldName);
1879 if (R == 0 || R->getValue() == 0)
1880 throw "Record `" + getName() + "' does not have a field named `" +
1881 FieldName.str() + "'!\n";
1883 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
1884 return DI->getDef();
1885 throw "Record `" + getName() + "', field `" + FieldName.str() +
1886 "' does not have a def initializer!";
1889 /// getValueAsBit - This method looks up the specified field and returns its
1890 /// value as a bit, throwing an exception if the field does not exist or if
1891 /// the value is not the right type.
1893 bool Record::getValueAsBit(StringRef FieldName) const {
1894 const RecordVal *R = getValue(FieldName);
1895 if (R == 0 || R->getValue() == 0)
1896 throw "Record `" + getName() + "' does not have a field named `" +
1897 FieldName.str() + "'!\n";
1899 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1900 return BI->getValue();
1901 throw "Record `" + getName() + "', field `" + FieldName.str() +
1902 "' does not have a bit initializer!";
1905 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1906 const RecordVal *R = getValue(FieldName);
1907 if (R == 0 || R->getValue() == 0)
1908 throw "Record `" + getName() + "' does not have a field named `" +
1909 FieldName.str() + "'!\n";
1911 if (R->getValue() == UnsetInit::get()) {
1916 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1917 return BI->getValue();
1918 throw "Record `" + getName() + "', field `" + FieldName.str() +
1919 "' does not have a bit initializer!";
1922 /// getValueAsDag - This method looks up the specified field and returns its
1923 /// value as an Dag, throwing an exception if the field does not exist or if
1924 /// the value is not the right type.
1926 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1927 const RecordVal *R = getValue(FieldName);
1928 if (R == 0 || R->getValue() == 0)
1929 throw "Record `" + getName() + "' does not have a field named `" +
1930 FieldName.str() + "'!\n";
1932 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
1934 throw "Record `" + getName() + "', field `" + FieldName.str() +
1935 "' does not have a dag initializer!";
1939 void MultiClass::dump() const {
1940 errs() << "Record:\n";
1943 errs() << "Defs:\n";
1944 for (RecordVector::const_iterator r = DefPrototypes.begin(),
1945 rend = DefPrototypes.end();
1953 void RecordKeeper::dump() const { errs() << *this; }
1955 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1956 OS << "------------- Classes -----------------\n";
1957 const std::map<std::string, Record*> &Classes = RK.getClasses();
1958 for (std::map<std::string, Record*>::const_iterator I = Classes.begin(),
1959 E = Classes.end(); I != E; ++I)
1960 OS << "class " << *I->second;
1962 OS << "------------- Defs -----------------\n";
1963 const std::map<std::string, Record*> &Defs = RK.getDefs();
1964 for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),
1965 E = Defs.end(); I != E; ++I)
1966 OS << "def " << *I->second;
1971 /// getAllDerivedDefinitions - This method returns all concrete definitions
1972 /// that derive from the specified class name. If a class with the specified
1973 /// name does not exist, an error is printed and true is returned.
1974 std::vector<Record*>
1975 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
1976 Record *Class = getClass(ClassName);
1978 throw "ERROR: Couldn't find the `" + ClassName + "' class!\n";
1980 std::vector<Record*> Defs;
1981 for (std::map<std::string, Record*>::const_iterator I = getDefs().begin(),
1982 E = getDefs().end(); I != E; ++I)
1983 if (I->second->isSubClassOf(Class))
1984 Defs.push_back(I->second);
1989 /// QualifyName - Return an Init with a qualifier prefix referring
1990 /// to CurRec's name.
1991 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1992 Init *Name, const std::string &Scoper) {
1993 RecTy *Type = dyn_cast<TypedInit>(Name)->getType();
1995 BinOpInit *NewName =
1996 BinOpInit::get(BinOpInit::STRCONCAT,
1997 BinOpInit::get(BinOpInit::STRCONCAT,
1998 CurRec.getNameInit(),
1999 StringInit::get(Scoper),
2000 Type)->Fold(&CurRec, CurMultiClass),
2004 if (CurMultiClass && Scoper != "::") {
2006 BinOpInit::get(BinOpInit::STRCONCAT,
2007 BinOpInit::get(BinOpInit::STRCONCAT,
2008 CurMultiClass->Rec.getNameInit(),
2009 StringInit::get("::"),
2010 Type)->Fold(&CurRec, CurMultiClass),
2011 NewName->Fold(&CurRec, CurMultiClass),
2015 return NewName->Fold(&CurRec, CurMultiClass);
2018 /// QualifyName - Return an Init with a qualifier prefix referring
2019 /// to CurRec's name.
2020 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2021 const std::string &Name,
2022 const std::string &Scoper) {
2023 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);