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/ADT/DenseMap.h"
16 #include "llvm/ADT/FoldingSet.h"
17 #include "llvm/ADT/Hashing.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/Support/DataTypes.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/Format.h"
25 #include "llvm/TableGen/Error.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.reset(new ListRecTy(this));
98 bool RecTy::baseClassOf(const RecTy *RHS) const{
99 assert (RHS && "NULL pointer");
100 return Kind == RHS->getRecTyKind();
103 Init *BitRecTy::convertValue(BitsInit *BI) {
104 if (BI->getNumBits() != 1) return nullptr; // Only accept if just one bit!
105 return BI->getBit(0);
108 Init *BitRecTy::convertValue(IntInit *II) {
109 int64_t Val = II->getValue();
110 if (Val != 0 && Val != 1) return nullptr; // Only accept 0 or 1 for a bit!
112 return BitInit::get(Val != 0);
115 Init *BitRecTy::convertValue(TypedInit *VI) {
116 RecTy *Ty = VI->getType();
117 if (isa<BitRecTy>(Ty))
118 return VI; // Accept variable if it is already of bit type!
119 if (auto *BitsTy = dyn_cast<BitsRecTy>(Ty))
120 // Accept only bits<1> expression.
121 return BitsTy->getNumBits() == 1 ? VI : nullptr;
122 // Ternary !if can be converted to bit, but only if both sides are
123 // convertible to a bit.
124 if (TernOpInit *TOI = dyn_cast<TernOpInit>(VI)) {
125 if (TOI->getOpcode() != TernOpInit::TernaryOp::IF)
127 if (!TOI->getMHS()->convertInitializerTo(BitRecTy::get()) ||
128 !TOI->getRHS()->convertInitializerTo(BitRecTy::get()))
135 bool BitRecTy::baseClassOf(const RecTy *RHS) const{
136 if(RecTy::baseClassOf(RHS) || RHS->getRecTyKind() == IntRecTyKind)
138 if(const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
139 return BitsTy->getNumBits() == 1;
143 BitsRecTy *BitsRecTy::get(unsigned Sz) {
144 static std::vector<std::unique_ptr<BitsRecTy>> Shared;
145 if (Sz >= Shared.size())
146 Shared.resize(Sz + 1);
147 std::unique_ptr<BitsRecTy> &Ty = Shared[Sz];
149 Ty.reset(new BitsRecTy(Sz));
153 std::string BitsRecTy::getAsString() const {
154 return "bits<" + utostr(Size) + ">";
157 Init *BitsRecTy::convertValue(UnsetInit *UI) {
158 SmallVector<Init *, 16> NewBits(Size);
160 for (unsigned i = 0; i != Size; ++i)
161 NewBits[i] = UnsetInit::get();
163 return BitsInit::get(NewBits);
166 Init *BitsRecTy::convertValue(BitInit *UI) {
167 if (Size != 1) return nullptr; // Can only convert single bit.
168 return BitsInit::get(UI);
171 /// canFitInBitfield - Return true if the number of bits is large enough to hold
172 /// the integer value.
173 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
174 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
175 return (NumBits >= sizeof(Value) * 8) ||
176 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
179 /// convertValue from Int initializer to bits type: Split the integer up into the
180 /// appropriate bits.
182 Init *BitsRecTy::convertValue(IntInit *II) {
183 int64_t Value = II->getValue();
184 // Make sure this bitfield is large enough to hold the integer value.
185 if (!canFitInBitfield(Value, Size))
188 SmallVector<Init *, 16> NewBits(Size);
190 for (unsigned i = 0; i != Size; ++i)
191 NewBits[i] = BitInit::get(Value & (1LL << i));
193 return BitsInit::get(NewBits);
196 Init *BitsRecTy::convertValue(BitsInit *BI) {
197 // If the number of bits is right, return it. Otherwise we need to expand or
199 if (BI->getNumBits() == Size) return BI;
203 Init *BitsRecTy::convertValue(TypedInit *VI) {
204 if (Size == 1 && isa<BitRecTy>(VI->getType()))
205 return BitsInit::get(VI);
207 if (VI->getType()->typeIsConvertibleTo(this)) {
208 SmallVector<Init *, 16> NewBits(Size);
210 for (unsigned i = 0; i != Size; ++i)
211 NewBits[i] = VarBitInit::get(VI, i);
212 return BitsInit::get(NewBits);
218 bool BitsRecTy::baseClassOf(const RecTy *RHS) const{
219 if (RecTy::baseClassOf(RHS)) //argument and the receiver are the same type
220 return cast<BitsRecTy>(RHS)->Size == Size;
221 RecTyKind kind = RHS->getRecTyKind();
222 return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
225 Init *IntRecTy::convertValue(BitInit *BI) {
226 return IntInit::get(BI->getValue());
229 Init *IntRecTy::convertValue(BitsInit *BI) {
231 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
232 if (BitInit *Bit = dyn_cast<BitInit>(BI->getBit(i))) {
233 Result |= Bit->getValue() << i;
237 return IntInit::get(Result);
240 Init *IntRecTy::convertValue(TypedInit *TI) {
241 if (TI->getType()->typeIsConvertibleTo(this))
242 return TI; // Accept variable if already of the right type!
246 bool IntRecTy::baseClassOf(const RecTy *RHS) const{
247 RecTyKind kind = RHS->getRecTyKind();
248 return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
251 Init *StringRecTy::convertValue(UnOpInit *BO) {
252 if (BO->getOpcode() == UnOpInit::CAST) {
253 Init *L = BO->getOperand()->convertInitializerTo(this);
254 if (!L) return nullptr;
255 if (L != BO->getOperand())
256 return UnOpInit::get(UnOpInit::CAST, L, StringRecTy::get());
260 return convertValue((TypedInit*)BO);
263 Init *StringRecTy::convertValue(BinOpInit *BO) {
264 if (BO->getOpcode() == BinOpInit::STRCONCAT) {
265 Init *L = BO->getLHS()->convertInitializerTo(this);
266 Init *R = BO->getRHS()->convertInitializerTo(this);
267 if (!L || !R) return nullptr;
268 if (L != BO->getLHS() || R != BO->getRHS())
269 return BinOpInit::get(BinOpInit::STRCONCAT, L, R, StringRecTy::get());
273 return convertValue((TypedInit*)BO);
277 Init *StringRecTy::convertValue(TypedInit *TI) {
278 if (isa<StringRecTy>(TI->getType()))
279 return TI; // Accept variable if already of the right type!
283 std::string ListRecTy::getAsString() const {
284 return "list<" + Ty->getAsString() + ">";
287 Init *ListRecTy::convertValue(ListInit *LI) {
288 std::vector<Init*> Elements;
290 // Verify that all of the elements of the list are subclasses of the
291 // appropriate class!
292 for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
293 if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
294 Elements.push_back(CI);
298 if (!isa<ListRecTy>(LI->getType()))
301 return ListInit::get(Elements, this);
304 Init *ListRecTy::convertValue(TypedInit *TI) {
305 // Ensure that TI is compatible with our class.
306 if (ListRecTy *LRT = dyn_cast<ListRecTy>(TI->getType()))
307 if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
312 bool ListRecTy::baseClassOf(const RecTy *RHS) const{
313 if(const ListRecTy* ListTy = dyn_cast<ListRecTy>(RHS))
314 return ListTy->getElementType()->typeIsConvertibleTo(Ty);
318 Init *DagRecTy::convertValue(TypedInit *TI) {
319 if (TI->getType()->typeIsConvertibleTo(this))
324 Init *DagRecTy::convertValue(UnOpInit *BO) {
325 if (BO->getOpcode() == UnOpInit::CAST) {
326 Init *L = BO->getOperand()->convertInitializerTo(this);
327 if (!L) return nullptr;
328 if (L != BO->getOperand())
329 return UnOpInit::get(UnOpInit::CAST, L, new DagRecTy);
335 Init *DagRecTy::convertValue(BinOpInit *BO) {
336 if (BO->getOpcode() == BinOpInit::CONCAT) {
337 Init *L = BO->getLHS()->convertInitializerTo(this);
338 Init *R = BO->getRHS()->convertInitializerTo(this);
339 if (!L || !R) return nullptr;
340 if (L != BO->getLHS() || R != BO->getRHS())
341 return BinOpInit::get(BinOpInit::CONCAT, L, R, new DagRecTy);
347 RecordRecTy *RecordRecTy::get(Record *R) {
348 return dyn_cast<RecordRecTy>(R->getDefInit()->getType());
351 std::string RecordRecTy::getAsString() const {
352 return Rec->getName();
355 Init *RecordRecTy::convertValue(DefInit *DI) {
356 // Ensure that DI is a subclass of Rec.
357 if (!DI->getDef()->isSubClassOf(Rec))
362 Init *RecordRecTy::convertValue(TypedInit *TI) {
363 // Ensure that TI is compatible with Rec.
364 if (RecordRecTy *RRT = dyn_cast<RecordRecTy>(TI->getType()))
365 if (RRT->getRecord()->isSubClassOf(getRecord()) ||
366 RRT->getRecord() == getRecord())
371 bool RecordRecTy::baseClassOf(const RecTy *RHS) const{
372 const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
376 if (Rec == RTy->getRecord() || RTy->getRecord()->isSubClassOf(Rec))
379 const std::vector<Record*> &SC = Rec->getSuperClasses();
380 for (unsigned i = 0, e = SC.size(); i != e; ++i)
381 if (RTy->getRecord()->isSubClassOf(SC[i]))
387 /// resolveTypes - Find a common type that T1 and T2 convert to.
388 /// Return null if no such type exists.
390 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
391 if (T1->typeIsConvertibleTo(T2))
393 if (T2->typeIsConvertibleTo(T1))
396 // If one is a Record type, check superclasses
397 if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
398 // See if T2 inherits from a type T1 also inherits from
399 for (Record *SuperRec1 : RecTy1->getRecord()->getSuperClasses()) {
400 RecordRecTy *SuperRecTy1 = RecordRecTy::get(SuperRec1);
401 RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
406 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) {
407 // See if T1 inherits from a type T2 also inherits from
408 for (Record *SuperRec2 : RecTy2->getRecord()->getSuperClasses()) {
409 RecordRecTy *SuperRecTy2 = RecordRecTy::get(SuperRec2);
410 RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
419 //===----------------------------------------------------------------------===//
420 // Initializer implementations
421 //===----------------------------------------------------------------------===//
423 void Init::anchor() { }
424 void Init::dump() const { return print(errs()); }
426 void UnsetInit::anchor() { }
428 UnsetInit *UnsetInit::get() {
429 static UnsetInit TheInit;
433 void BitInit::anchor() { }
435 BitInit *BitInit::get(bool V) {
436 static BitInit True(true);
437 static BitInit False(false);
439 return V ? &True : &False;
443 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
444 ID.AddInteger(Range.size());
446 for (Init *I : Range)
450 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
451 static FoldingSet<BitsInit> ThePool;
452 static std::vector<std::unique_ptr<BitsInit>> TheActualPool;
455 ProfileBitsInit(ID, Range);
458 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
461 BitsInit *I = new BitsInit(Range);
462 ThePool.InsertNode(I, IP);
463 TheActualPool.push_back(std::unique_ptr<BitsInit>(I));
467 void BitsInit::Profile(FoldingSetNodeID &ID) const {
468 ProfileBitsInit(ID, Bits);
472 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
473 SmallVector<Init *, 16> NewBits(Bits.size());
475 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
476 if (Bits[i] >= getNumBits())
478 NewBits[i] = getBit(Bits[i]);
480 return BitsInit::get(NewBits);
483 std::string BitsInit::getAsString() const {
484 std::string Result = "{ ";
485 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
486 if (i) Result += ", ";
487 if (Init *Bit = getBit(e-i-1))
488 Result += Bit->getAsString();
492 return Result + " }";
495 // Fix bit initializer to preserve the behavior that bit reference from a unset
496 // bits initializer will resolve into VarBitInit to keep the field name and bit
497 // number used in targets with fixed insn length.
498 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
499 if (RV || !isa<UnsetInit>(After))
504 // resolveReferences - If there are any field references that refer to fields
505 // that have been filled in, we can propagate the values now.
507 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
508 bool Changed = false;
509 SmallVector<Init *, 16> NewBits(getNumBits());
511 Init *CachedInit = nullptr;
512 Init *CachedBitVar = nullptr;
513 bool CachedBitVarChanged = false;
515 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
516 Init *CurBit = Bits[i];
517 Init *CurBitVar = CurBit->getBitVar();
521 if (CurBitVar == CachedBitVar) {
522 if (CachedBitVarChanged) {
523 Init *Bit = CachedInit->getBit(CurBit->getBitNum());
524 NewBits[i] = fixBitInit(RV, CurBit, Bit);
528 CachedBitVar = CurBitVar;
529 CachedBitVarChanged = false;
534 CurBitVar = CurBitVar->resolveReferences(R, RV);
535 CachedBitVarChanged |= B != CurBitVar;
536 Changed |= B != CurBitVar;
537 } while (B != CurBitVar);
538 CachedInit = CurBitVar;
540 if (CachedBitVarChanged) {
541 Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
542 NewBits[i] = fixBitInit(RV, CurBit, Bit);
547 return BitsInit::get(NewBits);
549 return const_cast<BitsInit *>(this);
552 IntInit *IntInit::get(int64_t V) {
553 static DenseMap<int64_t, std::unique_ptr<IntInit>> ThePool;
555 std::unique_ptr<IntInit> &I = ThePool[V];
556 if (!I) I.reset(new IntInit(V));
560 std::string IntInit::getAsString() const {
561 return itostr(Value);
565 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
566 SmallVector<Init *, 16> NewBits(Bits.size());
568 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
572 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
574 return BitsInit::get(NewBits);
577 void StringInit::anchor() { }
579 StringInit *StringInit::get(StringRef V) {
580 static StringMap<std::unique_ptr<StringInit>> ThePool;
582 std::unique_ptr<StringInit> &I = ThePool[V];
583 if (!I) I.reset(new StringInit(V));
587 static void ProfileListInit(FoldingSetNodeID &ID,
588 ArrayRef<Init *> Range,
590 ID.AddInteger(Range.size());
591 ID.AddPointer(EltTy);
593 for (Init *I : Range)
597 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
598 static FoldingSet<ListInit> ThePool;
599 static std::vector<std::unique_ptr<ListInit>> TheActualPool;
602 ProfileListInit(ID, Range, EltTy);
605 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
608 ListInit *I = new ListInit(Range, EltTy);
609 ThePool.InsertNode(I, IP);
610 TheActualPool.push_back(std::unique_ptr<ListInit>(I));
614 void ListInit::Profile(FoldingSetNodeID &ID) const {
615 RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
617 ProfileListInit(ID, Values, EltTy);
621 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
622 std::vector<Init*> Vals;
623 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
624 if (Elements[i] >= getSize())
626 Vals.push_back(getElement(Elements[i]));
628 return ListInit::get(Vals, getType());
631 Record *ListInit::getElementAsRecord(unsigned i) const {
632 assert(i < Values.size() && "List element index out of range!");
633 DefInit *DI = dyn_cast<DefInit>(Values[i]);
635 PrintFatalError("Expected record in list!");
639 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
640 std::vector<Init*> Resolved;
641 Resolved.reserve(getSize());
642 bool Changed = false;
644 for (unsigned i = 0, e = getSize(); i != e; ++i) {
646 Init *CurElt = getElement(i);
650 CurElt = CurElt->resolveReferences(R, RV);
651 Changed |= E != CurElt;
652 } while (E != CurElt);
653 Resolved.push_back(E);
657 return ListInit::get(Resolved, getType());
658 return const_cast<ListInit *>(this);
661 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
662 unsigned Elt) const {
663 if (Elt >= getSize())
664 return nullptr; // Out of range reference.
665 Init *E = getElement(Elt);
666 // If the element is set to some value, or if we are resolving a reference
667 // to a specific variable and that variable is explicitly unset, then
668 // replace the VarListElementInit with it.
669 if (IRV || !isa<UnsetInit>(E))
674 std::string ListInit::getAsString() const {
675 std::string Result = "[";
676 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
677 if (i) Result += ", ";
678 Result += Values[i]->getAsString();
683 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
684 unsigned Elt) const {
685 Init *Resolved = resolveReferences(R, IRV);
686 OpInit *OResolved = dyn_cast<OpInit>(Resolved);
688 Resolved = OResolved->Fold(&R, nullptr);
691 if (Resolved != this) {
692 TypedInit *Typed = cast<TypedInit>(Resolved);
693 if (Init *New = Typed->resolveListElementReference(R, IRV, Elt))
695 return VarListElementInit::get(Typed, Elt);
701 Init *OpInit::getBit(unsigned Bit) const {
702 if (getType() == BitRecTy::get())
703 return const_cast<OpInit*>(this);
704 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
707 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
708 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
709 static DenseMap<Key, std::unique_ptr<UnOpInit>> ThePool;
711 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
713 std::unique_ptr<UnOpInit> &I = ThePool[TheKey];
714 if (!I) I.reset(new UnOpInit(opc, lhs, Type));
718 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
719 switch (getOpcode()) {
721 if (getType()->getAsString() == "string") {
722 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
725 if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
726 return StringInit::get(LHSd->getDef()->getName());
728 if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
729 return StringInit::get(LHSi->getAsString());
731 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
732 std::string Name = LHSs->getValue();
734 // From TGParser::ParseIDValue
736 if (const RecordVal *RV = CurRec->getValue(Name)) {
737 if (RV->getType() != getType())
738 PrintFatalError("type mismatch in cast");
739 return VarInit::get(Name, RV->getType());
742 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
745 if (CurRec->isTemplateArg(TemplateArgName)) {
746 const RecordVal *RV = CurRec->getValue(TemplateArgName);
747 assert(RV && "Template arg doesn't exist??");
749 if (RV->getType() != getType())
750 PrintFatalError("type mismatch in cast");
752 return VarInit::get(TemplateArgName, RV->getType());
757 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
759 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
760 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
761 assert(RV && "Template arg doesn't exist??");
763 if (RV->getType() != getType())
764 PrintFatalError("type mismatch in cast");
766 return VarInit::get(MCName, RV->getType());
769 assert(CurRec && "NULL pointer");
770 if (Record *D = (CurRec->getRecords()).getDef(Name))
771 return DefInit::get(D);
773 PrintFatalError(CurRec->getLoc(),
774 "Undefined reference:'" + Name + "'\n");
780 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
781 assert(LHSl->getSize() != 0 && "Empty list in car");
782 return LHSl->getElement(0);
787 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
788 assert(LHSl->getSize() != 0 && "Empty list in cdr");
789 // Note the +1. We can't just pass the result of getValues()
791 ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
792 ArrayRef<Init *>::iterator end = LHSl->getValues().end();
794 ListInit::get(ArrayRef<Init *>(begin, end - begin),
801 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
802 if (LHSl->getSize() == 0) {
803 return IntInit::get(1);
805 return IntInit::get(0);
808 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
809 if (LHSs->getValue().empty()) {
810 return IntInit::get(1);
812 return IntInit::get(0);
819 return const_cast<UnOpInit *>(this);
822 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
823 Init *lhs = LHS->resolveReferences(R, RV);
826 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, nullptr);
827 return Fold(&R, nullptr);
830 std::string UnOpInit::getAsString() const {
833 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
834 case HEAD: Result = "!head"; break;
835 case TAIL: Result = "!tail"; break;
836 case EMPTY: Result = "!empty"; break;
838 return Result + "(" + LHS->getAsString() + ")";
841 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
842 Init *rhs, RecTy *Type) {
844 std::pair<std::pair<unsigned, Init *>, Init *>,
848 static DenseMap<Key, std::unique_ptr<BinOpInit>> ThePool;
850 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
853 std::unique_ptr<BinOpInit> &I = ThePool[TheKey];
854 if (!I) I.reset(new BinOpInit(opc, lhs, rhs, Type));
858 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
859 switch (getOpcode()) {
861 DagInit *LHSs = dyn_cast<DagInit>(LHS);
862 DagInit *RHSs = dyn_cast<DagInit>(RHS);
864 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
865 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
866 if (!LOp || !ROp || LOp->getDef() != ROp->getDef())
867 PrintFatalError("Concated Dag operators do not match!");
868 std::vector<Init*> Args;
869 std::vector<std::string> ArgNames;
870 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
871 Args.push_back(LHSs->getArg(i));
872 ArgNames.push_back(LHSs->getArgName(i));
874 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
875 Args.push_back(RHSs->getArg(i));
876 ArgNames.push_back(RHSs->getArgName(i));
878 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
883 ListInit *LHSs = dyn_cast<ListInit>(LHS);
884 ListInit *RHSs = dyn_cast<ListInit>(RHS);
886 std::vector<Init *> Args;
887 Args.insert(Args.end(), LHSs->begin(), LHSs->end());
888 Args.insert(Args.end(), RHSs->begin(), RHSs->end());
889 return ListInit::get(
890 Args, static_cast<ListRecTy *>(LHSs->getType())->getElementType());
895 StringInit *LHSs = dyn_cast<StringInit>(LHS);
896 StringInit *RHSs = dyn_cast<StringInit>(RHS);
898 return StringInit::get(LHSs->getValue() + RHSs->getValue());
902 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
903 // to string objects.
905 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
907 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
910 return IntInit::get(L->getValue() == R->getValue());
912 StringInit *LHSs = dyn_cast<StringInit>(LHS);
913 StringInit *RHSs = dyn_cast<StringInit>(RHS);
915 // Make sure we've resolved
917 return IntInit::get(LHSs->getValue() == RHSs->getValue());
927 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
929 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
931 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
933 switch (getOpcode()) {
934 default: llvm_unreachable("Bad opcode!");
935 case ADD: Result = LHSv + RHSv; break;
936 case AND: Result = LHSv & RHSv; break;
937 case SHL: Result = LHSv << RHSv; break;
938 case SRA: Result = LHSv >> RHSv; break;
939 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
941 return IntInit::get(Result);
946 return const_cast<BinOpInit *>(this);
949 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
950 Init *lhs = LHS->resolveReferences(R, RV);
951 Init *rhs = RHS->resolveReferences(R, RV);
953 if (LHS != lhs || RHS != rhs)
954 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R,nullptr);
955 return Fold(&R, nullptr);
958 std::string BinOpInit::getAsString() const {
961 case CONCAT: Result = "!con"; break;
962 case ADD: Result = "!add"; break;
963 case AND: Result = "!and"; break;
964 case SHL: Result = "!shl"; break;
965 case SRA: Result = "!sra"; break;
966 case SRL: Result = "!srl"; break;
967 case EQ: Result = "!eq"; break;
968 case LISTCONCAT: Result = "!listconcat"; break;
969 case STRCONCAT: Result = "!strconcat"; break;
971 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
974 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs,
975 Init *mhs, Init *rhs,
979 std::pair<std::pair<unsigned, RecTy *>, Init *>,
985 static DenseMap<Key, std::unique_ptr<TernOpInit>> ThePool;
987 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
993 std::unique_ptr<TernOpInit> &I = ThePool[TheKey];
994 if (!I) I.reset(new TernOpInit(opc, lhs, mhs, rhs, Type));
998 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
999 Record *CurRec, MultiClass *CurMultiClass);
1001 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
1002 RecTy *Type, Record *CurRec,
1003 MultiClass *CurMultiClass) {
1004 // If this is a dag, recurse
1005 if (auto *TArg = dyn_cast<TypedInit>(Arg))
1006 if (TArg->getType()->getAsString() == "dag")
1007 return ForeachHelper(LHS, Arg, RHSo, Type, CurRec, CurMultiClass);
1009 std::vector<Init *> NewOperands;
1010 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
1011 if (auto *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i))) {
1012 if (Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1013 Type, CurRec, CurMultiClass))
1014 NewOperands.push_back(Result);
1016 NewOperands.push_back(Arg);
1017 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1018 NewOperands.push_back(Arg);
1020 NewOperands.push_back(RHSo->getOperand(i));
1024 // Now run the operator and use its result as the new leaf
1025 const OpInit *NewOp = RHSo->clone(NewOperands);
1026 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
1027 return (NewVal != NewOp) ? NewVal : nullptr;
1030 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1031 Record *CurRec, MultiClass *CurMultiClass) {
1032 DagInit *MHSd = dyn_cast<DagInit>(MHS);
1033 ListInit *MHSl = dyn_cast<ListInit>(MHS);
1035 OpInit *RHSo = dyn_cast<OpInit>(RHS);
1038 PrintFatalError(CurRec->getLoc(), "!foreach requires an operator\n");
1041 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1044 PrintFatalError(CurRec->getLoc(), "!foreach requires typed variable\n");
1046 if ((MHSd && isa<DagRecTy>(Type)) || (MHSl && isa<ListRecTy>(Type))) {
1048 Init *Val = MHSd->getOperator();
1049 Init *Result = EvaluateOperation(RHSo, LHS, Val,
1050 Type, CurRec, CurMultiClass);
1055 std::vector<std::pair<Init *, std::string> > args;
1056 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1058 std::string ArgName;
1059 Arg = MHSd->getArg(i);
1060 ArgName = MHSd->getArgName(i);
1063 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1064 CurRec, CurMultiClass);
1069 // TODO: Process arg names
1070 args.push_back(std::make_pair(Arg, ArgName));
1073 return DagInit::get(Val, "", args);
1076 std::vector<Init *> NewOperands;
1077 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1079 for (Init *&Item : NewList) {
1080 NewOperands.clear();
1081 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1082 // First, replace the foreach variable with the list item
1083 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1084 NewOperands.push_back(Item);
1086 NewOperands.push_back(RHSo->getOperand(i));
1090 // Now run the operator and use its result as the new list item
1091 const OpInit *NewOp = RHSo->clone(NewOperands);
1092 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1093 if (NewItem != NewOp)
1096 return ListInit::get(NewList, MHSl->getType());
1102 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1103 switch (getOpcode()) {
1105 DefInit *LHSd = dyn_cast<DefInit>(LHS);
1106 VarInit *LHSv = dyn_cast<VarInit>(LHS);
1107 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1109 DefInit *MHSd = dyn_cast<DefInit>(MHS);
1110 VarInit *MHSv = dyn_cast<VarInit>(MHS);
1111 StringInit *MHSs = dyn_cast<StringInit>(MHS);
1113 DefInit *RHSd = dyn_cast<DefInit>(RHS);
1114 VarInit *RHSv = dyn_cast<VarInit>(RHS);
1115 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1117 if ((LHSd && MHSd && RHSd)
1118 || (LHSv && MHSv && RHSv)
1119 || (LHSs && MHSs && RHSs)) {
1121 Record *Val = RHSd->getDef();
1122 if (LHSd->getAsString() == RHSd->getAsString()) {
1123 Val = MHSd->getDef();
1125 return DefInit::get(Val);
1128 std::string Val = RHSv->getName();
1129 if (LHSv->getAsString() == RHSv->getAsString()) {
1130 Val = MHSv->getName();
1132 return VarInit::get(Val, getType());
1135 std::string Val = RHSs->getValue();
1137 std::string::size_type found;
1138 std::string::size_type idx = 0;
1140 found = Val.find(LHSs->getValue(), idx);
1141 if (found != std::string::npos) {
1142 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1144 idx = found + MHSs->getValue().size();
1145 } while (found != std::string::npos);
1147 return StringInit::get(Val);
1154 Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1155 CurRec, CurMultiClass);
1163 IntInit *LHSi = dyn_cast<IntInit>(LHS);
1164 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1165 LHSi = dyn_cast<IntInit>(I);
1167 if (LHSi->getValue()) {
1177 return const_cast<TernOpInit *>(this);
1180 Init *TernOpInit::resolveReferences(Record &R,
1181 const RecordVal *RV) const {
1182 Init *lhs = LHS->resolveReferences(R, RV);
1184 if (Opc == IF && lhs != LHS) {
1185 IntInit *Value = dyn_cast<IntInit>(lhs);
1186 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1187 Value = dyn_cast<IntInit>(I);
1190 if (Value->getValue()) {
1191 Init *mhs = MHS->resolveReferences(R, RV);
1192 return (TernOpInit::get(getOpcode(), lhs, mhs,
1193 RHS, getType()))->Fold(&R, nullptr);
1195 Init *rhs = RHS->resolveReferences(R, RV);
1196 return (TernOpInit::get(getOpcode(), lhs, MHS,
1197 rhs, getType()))->Fold(&R, nullptr);
1202 Init *mhs = MHS->resolveReferences(R, RV);
1203 Init *rhs = RHS->resolveReferences(R, RV);
1205 if (LHS != lhs || MHS != mhs || RHS != rhs)
1206 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1207 getType()))->Fold(&R, nullptr);
1208 return Fold(&R, nullptr);
1211 std::string TernOpInit::getAsString() const {
1214 case SUBST: Result = "!subst"; break;
1215 case FOREACH: Result = "!foreach"; break;
1216 case IF: Result = "!if"; break;
1218 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
1219 + RHS->getAsString() + ")";
1222 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1223 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
1224 if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
1225 return Field->getType();
1230 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1231 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1232 if (!T) return nullptr; // Cannot subscript a non-bits variable.
1233 unsigned NumBits = T->getNumBits();
1235 SmallVector<Init *, 16> NewBits(Bits.size());
1236 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1237 if (Bits[i] >= NumBits)
1240 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1242 return BitsInit::get(NewBits);
1246 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1247 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1248 if (!T) return nullptr; // Cannot subscript a non-list variable.
1250 if (Elements.size() == 1)
1251 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1253 std::vector<Init*> ListInits;
1254 ListInits.reserve(Elements.size());
1255 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1256 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1258 return ListInit::get(ListInits, T);
1262 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1263 Init *Value = StringInit::get(VN);
1264 return VarInit::get(Value, T);
1267 VarInit *VarInit::get(Init *VN, RecTy *T) {
1268 typedef std::pair<RecTy *, Init *> Key;
1269 static DenseMap<Key, std::unique_ptr<VarInit>> ThePool;
1271 Key TheKey(std::make_pair(T, VN));
1273 std::unique_ptr<VarInit> &I = ThePool[TheKey];
1274 if (!I) I.reset(new VarInit(VN, T));
1278 const std::string &VarInit::getName() const {
1279 StringInit *NameString = cast<StringInit>(getNameInit());
1280 return NameString->getValue();
1283 Init *VarInit::getBit(unsigned Bit) const {
1284 if (getType() == BitRecTy::get())
1285 return const_cast<VarInit*>(this);
1286 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1289 Init *VarInit::resolveListElementReference(Record &R,
1290 const RecordVal *IRV,
1291 unsigned Elt) const {
1292 if (R.isTemplateArg(getNameInit())) return nullptr;
1293 if (IRV && IRV->getNameInit() != getNameInit()) return nullptr;
1295 RecordVal *RV = R.getValue(getNameInit());
1296 assert(RV && "Reference to a non-existent variable?");
1297 ListInit *LI = dyn_cast<ListInit>(RV->getValue());
1299 TypedInit *VI = cast<TypedInit>(RV->getValue());
1300 return VarListElementInit::get(VI, Elt);
1303 if (Elt >= LI->getSize())
1304 return nullptr; // 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 && !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 static DenseMap<Key, std::unique_ptr<VarBitInit>> ThePool;
1354 Key TheKey(std::make_pair(T, B));
1356 std::unique_ptr<VarBitInit> &I = ThePool[TheKey];
1357 if (!I) I.reset(new VarBitInit(T, B));
1361 std::string VarBitInit::getAsString() const {
1362 return TI->getAsString() + "{" + utostr(Bit) + "}";
1365 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1366 Init *I = TI->resolveReferences(R, RV);
1368 return I->getBit(getBitNum());
1370 return const_cast<VarBitInit*>(this);
1373 VarListElementInit *VarListElementInit::get(TypedInit *T,
1375 typedef std::pair<TypedInit *, unsigned> Key;
1376 static DenseMap<Key, std::unique_ptr<VarListElementInit>> ThePool;
1378 Key TheKey(std::make_pair(T, E));
1380 std::unique_ptr<VarListElementInit> &I = ThePool[TheKey];
1381 if (!I) I.reset(new VarListElementInit(T, E));
1385 std::string VarListElementInit::getAsString() const {
1386 return TI->getAsString() + "[" + utostr(Element) + "]";
1390 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1391 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1394 return const_cast<VarListElementInit *>(this);
1397 Init *VarListElementInit::getBit(unsigned Bit) const {
1398 if (getType() == BitRecTy::get())
1399 return const_cast<VarListElementInit*>(this);
1400 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1403 Init *VarListElementInit:: resolveListElementReference(Record &R,
1404 const RecordVal *RV,
1405 unsigned Elt) const {
1406 Init *Result = TI->resolveListElementReference(R, RV, Element);
1409 if (TypedInit *TInit = dyn_cast<TypedInit>(Result)) {
1410 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1411 if (Result2) return Result2;
1412 return VarListElementInit::get(TInit, Elt);
1420 DefInit *DefInit::get(Record *R) {
1421 return R->getDefInit();
1424 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1425 if (const RecordVal *RV = Def->getValue(FieldName))
1426 return RV->getType();
1430 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1431 const std::string &FieldName) const {
1432 return Def->getValue(FieldName)->getValue();
1436 std::string DefInit::getAsString() const {
1437 return Def->getName();
1440 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1441 typedef std::pair<Init *, TableGenStringKey> Key;
1442 static DenseMap<Key, std::unique_ptr<FieldInit>> ThePool;
1444 Key TheKey(std::make_pair(R, FN));
1446 std::unique_ptr<FieldInit> &I = ThePool[TheKey];
1447 if (!I) I.reset(new FieldInit(R, FN));
1451 Init *FieldInit::getBit(unsigned Bit) const {
1452 if (getType() == BitRecTy::get())
1453 return const_cast<FieldInit*>(this);
1454 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1457 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1458 unsigned Elt) const {
1459 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1460 if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
1461 if (Elt >= LI->getSize()) return nullptr;
1462 Init *E = LI->getElement(Elt);
1464 // If the element is set to some value, or if we are resolving a
1465 // reference to a specific variable and that variable is explicitly
1466 // unset, then replace the VarListElementInit with it.
1467 if (RV || !isa<UnsetInit>(E))
1473 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1474 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1476 Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1478 Init *BVR = BitsVal->resolveReferences(R, RV);
1479 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1482 if (NewRec != Rec) {
1483 return FieldInit::get(NewRec, FieldName);
1485 return const_cast<FieldInit *>(this);
1488 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, const std::string &VN,
1489 ArrayRef<Init *> ArgRange,
1490 ArrayRef<std::string> NameRange) {
1494 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1495 ArrayRef<std::string>::iterator Name = NameRange.begin();
1496 while (Arg != ArgRange.end()) {
1497 assert(Name != NameRange.end() && "Arg name underflow!");
1498 ID.AddPointer(*Arg++);
1499 ID.AddString(*Name++);
1501 assert(Name == NameRange.end() && "Arg name overflow!");
1505 DagInit::get(Init *V, const std::string &VN,
1506 ArrayRef<Init *> ArgRange,
1507 ArrayRef<std::string> NameRange) {
1508 static FoldingSet<DagInit> ThePool;
1509 static std::vector<std::unique_ptr<DagInit>> TheActualPool;
1511 FoldingSetNodeID ID;
1512 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1515 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1518 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1519 ThePool.InsertNode(I, IP);
1520 TheActualPool.push_back(std::unique_ptr<DagInit>(I));
1525 DagInit::get(Init *V, const std::string &VN,
1526 const std::vector<std::pair<Init*, std::string> > &args) {
1527 std::vector<Init *> Args;
1528 std::vector<std::string> Names;
1530 for (const auto &Arg : args) {
1531 Args.push_back(Arg.first);
1532 Names.push_back(Arg.second);
1535 return DagInit::get(V, VN, Args, Names);
1538 void DagInit::Profile(FoldingSetNodeID &ID) const {
1539 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1542 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1543 std::vector<Init*> NewArgs;
1544 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1545 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1547 Init *Op = Val->resolveReferences(R, RV);
1549 if (Args != NewArgs || Op != Val)
1550 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1552 return const_cast<DagInit *>(this);
1556 std::string DagInit::getAsString() const {
1557 std::string Result = "(" + Val->getAsString();
1558 if (!ValName.empty())
1559 Result += ":" + ValName;
1560 if (!Args.empty()) {
1561 Result += " " + Args[0]->getAsString();
1562 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1563 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1564 Result += ", " + Args[i]->getAsString();
1565 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1568 return Result + ")";
1572 //===----------------------------------------------------------------------===//
1573 // Other implementations
1574 //===----------------------------------------------------------------------===//
1576 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1577 : Name(N), Ty(T), Prefix(P) {
1578 Value = Ty->convertValue(UnsetInit::get());
1579 assert(Value && "Cannot create unset value for current type!");
1582 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1583 : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1584 Value = Ty->convertValue(UnsetInit::get());
1585 assert(Value && "Cannot create unset value for current type!");
1588 const std::string &RecordVal::getName() const {
1589 return cast<StringInit>(Name)->getValue();
1592 void RecordVal::dump() const { errs() << *this; }
1594 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1595 if (getPrefix()) OS << "field ";
1596 OS << *getType() << " " << getNameInitAsString();
1599 OS << " = " << *getValue();
1601 if (PrintSem) OS << ";\n";
1604 unsigned Record::LastID = 0;
1606 void Record::init() {
1609 // Every record potentially has a def at the top. This value is
1610 // replaced with the top-level def name at instantiation time.
1611 RecordVal DN("NAME", StringRecTy::get(), 0);
1615 void Record::checkName() {
1616 // Ensure the record name has string type.
1617 const TypedInit *TypedName = cast<const TypedInit>(Name);
1618 RecTy *Type = TypedName->getType();
1619 if (!isa<StringRecTy>(Type))
1620 PrintFatalError(getLoc(), "Record name is not a string!");
1623 DefInit *Record::getDefInit() {
1624 static DenseMap<Record *, std::unique_ptr<DefInit>> ThePool;
1628 std::unique_ptr<DefInit> &I = ThePool[this];
1629 if (!I) I.reset(new DefInit(this, new RecordRecTy(this)));
1633 const std::string &Record::getName() const {
1634 return cast<StringInit>(Name)->getValue();
1637 void Record::setName(Init *NewName) {
1640 // DO NOT resolve record values to the name at this point because
1641 // there might be default values for arguments of this def. Those
1642 // arguments might not have been resolved yet so we don't want to
1643 // prematurely assume values for those arguments were not passed to
1646 // Nonetheless, it may be that some of this Record's values
1647 // reference the record name. Indeed, the reason for having the
1648 // record name be an Init is to provide this flexibility. The extra
1649 // resolve steps after completely instantiating defs takes care of
1650 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1653 void Record::setName(const std::string &Name) {
1654 setName(StringInit::get(Name));
1657 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1658 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1660 void Record::resolveReferencesTo(const RecordVal *RV) {
1661 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1662 if (RV == &Values[i]) // Skip resolve the same field as the given one
1664 if (Init *V = Values[i].getValue())
1665 if (Values[i].setValue(V->resolveReferences(*this, RV)))
1666 PrintFatalError(getLoc(), "Invalid value is found when setting '"
1667 + Values[i].getNameInitAsString()
1668 + "' after resolving references"
1669 + (RV ? " against '" + RV->getNameInitAsString()
1671 + RV->getValue()->getAsUnquotedString() + ")"
1675 Init *OldName = getNameInit();
1676 Init *NewName = Name->resolveReferences(*this, RV);
1677 if (NewName != OldName) {
1678 // Re-register with RecordKeeper.
1683 void Record::dump() const { errs() << *this; }
1685 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1686 OS << R.getNameInitAsString();
1688 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1689 if (!TArgs.empty()) {
1691 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1693 const RecordVal *RV = R.getValue(TArgs[i]);
1694 assert(RV && "Template argument record not found??");
1695 RV->print(OS, false);
1701 const std::vector<Record*> &SC = R.getSuperClasses();
1704 for (unsigned i = 0, e = SC.size(); i != e; ++i)
1705 OS << " " << SC[i]->getNameInitAsString();
1709 const std::vector<RecordVal> &Vals = R.getValues();
1710 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1711 if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1713 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1714 if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1720 /// getValueInit - Return the initializer for a value with the specified name,
1721 /// or abort if the field does not exist.
1723 Init *Record::getValueInit(StringRef FieldName) const {
1724 const RecordVal *R = getValue(FieldName);
1725 if (!R || !R->getValue())
1726 PrintFatalError(getLoc(), "Record `" + getName() +
1727 "' does not have a field named `" + FieldName + "'!\n");
1728 return R->getValue();
1732 /// getValueAsString - This method looks up the specified field and returns its
1733 /// value as a string, aborts if the field does not exist or if
1734 /// the value is not a string.
1736 std::string Record::getValueAsString(StringRef FieldName) const {
1737 const RecordVal *R = getValue(FieldName);
1738 if (!R || !R->getValue())
1739 PrintFatalError(getLoc(), "Record `" + getName() +
1740 "' does not have a field named `" + FieldName + "'!\n");
1742 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1743 return SI->getValue();
1744 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1745 FieldName + "' does not have a string initializer!");
1748 /// getValueAsBitsInit - This method looks up the specified field and returns
1749 /// its value as a BitsInit, aborts if the field does not exist or if
1750 /// the value is not the right type.
1752 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1753 const RecordVal *R = getValue(FieldName);
1754 if (!R || !R->getValue())
1755 PrintFatalError(getLoc(), "Record `" + getName() +
1756 "' does not have a field named `" + FieldName + "'!\n");
1758 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
1760 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1761 FieldName + "' does not have a BitsInit initializer!");
1764 /// getValueAsListInit - This method looks up the specified field and returns
1765 /// its value as a ListInit, aborting if the field does not exist or if
1766 /// the value is not the right type.
1768 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1769 const RecordVal *R = getValue(FieldName);
1770 if (!R || !R->getValue())
1771 PrintFatalError(getLoc(), "Record `" + getName() +
1772 "' does not have a field named `" + FieldName + "'!\n");
1774 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
1776 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1777 FieldName + "' does not have a list initializer!");
1780 /// getValueAsListOfDefs - This method looks up the specified field and returns
1781 /// its value as a vector of records, aborting if the field does not exist
1782 /// or if the value is not the right type.
1784 std::vector<Record*>
1785 Record::getValueAsListOfDefs(StringRef FieldName) const {
1786 ListInit *List = getValueAsListInit(FieldName);
1787 std::vector<Record*> Defs;
1788 for (unsigned i = 0; i < List->getSize(); i++) {
1789 if (DefInit *DI = dyn_cast<DefInit>(List->getElement(i))) {
1790 Defs.push_back(DI->getDef());
1792 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1793 FieldName + "' list is not entirely DefInit!");
1799 /// getValueAsInt - This method looks up the specified field and returns its
1800 /// value as an int64_t, aborting if the field does not exist or if the value
1801 /// is not the right type.
1803 int64_t Record::getValueAsInt(StringRef FieldName) const {
1804 const RecordVal *R = getValue(FieldName);
1805 if (!R || !R->getValue())
1806 PrintFatalError(getLoc(), "Record `" + getName() +
1807 "' does not have a field named `" + FieldName + "'!\n");
1809 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
1810 return II->getValue();
1811 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1812 FieldName + "' does not have an int initializer!");
1815 /// getValueAsListOfInts - This method looks up the specified field and returns
1816 /// its value as a vector of integers, aborting if the field does not exist or
1817 /// if the value is not the right type.
1819 std::vector<int64_t>
1820 Record::getValueAsListOfInts(StringRef FieldName) const {
1821 ListInit *List = getValueAsListInit(FieldName);
1822 std::vector<int64_t> Ints;
1823 for (unsigned i = 0; i < List->getSize(); i++) {
1824 if (IntInit *II = dyn_cast<IntInit>(List->getElement(i))) {
1825 Ints.push_back(II->getValue());
1827 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1828 FieldName + "' does not have a list of ints initializer!");
1834 /// getValueAsListOfStrings - This method looks up the specified field and
1835 /// returns its value as a vector of strings, aborting if the field does not
1836 /// exist or if the value is not the right type.
1838 std::vector<std::string>
1839 Record::getValueAsListOfStrings(StringRef FieldName) const {
1840 ListInit *List = getValueAsListInit(FieldName);
1841 std::vector<std::string> Strings;
1842 for (unsigned i = 0; i < List->getSize(); i++) {
1843 if (StringInit *II = dyn_cast<StringInit>(List->getElement(i))) {
1844 Strings.push_back(II->getValue());
1846 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1847 FieldName + "' does not have a list of strings initializer!");
1853 /// getValueAsDef - This method looks up the specified field and returns its
1854 /// value as a Record, aborting if the field does not exist or if the value
1855 /// is not the right type.
1857 Record *Record::getValueAsDef(StringRef FieldName) const {
1858 const RecordVal *R = getValue(FieldName);
1859 if (!R || !R->getValue())
1860 PrintFatalError(getLoc(), "Record `" + getName() +
1861 "' does not have a field named `" + FieldName + "'!\n");
1863 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
1864 return DI->getDef();
1865 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1866 FieldName + "' does not have a def initializer!");
1869 /// getValueAsBit - This method looks up the specified field and returns its
1870 /// value as a bit, aborting if the field does not exist or if the value is
1871 /// not the right type.
1873 bool Record::getValueAsBit(StringRef FieldName) const {
1874 const RecordVal *R = getValue(FieldName);
1875 if (!R || !R->getValue())
1876 PrintFatalError(getLoc(), "Record `" + getName() +
1877 "' does not have a field named `" + FieldName + "'!\n");
1879 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1880 return BI->getValue();
1881 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1882 FieldName + "' does not have a bit initializer!");
1885 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1886 const RecordVal *R = getValue(FieldName);
1887 if (!R || !R->getValue())
1888 PrintFatalError(getLoc(), "Record `" + getName() +
1889 "' does not have a field named `" + FieldName.str() + "'!\n");
1891 if (isa<UnsetInit>(R->getValue())) {
1896 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1897 return BI->getValue();
1898 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1899 FieldName + "' does not have a bit initializer!");
1902 /// getValueAsDag - This method looks up the specified field and returns its
1903 /// value as an Dag, aborting if the field does not exist or if the value is
1904 /// not the right type.
1906 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1907 const RecordVal *R = getValue(FieldName);
1908 if (!R || !R->getValue())
1909 PrintFatalError(getLoc(), "Record `" + getName() +
1910 "' does not have a field named `" + FieldName + "'!\n");
1912 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
1914 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1915 FieldName + "' does not have a dag initializer!");
1919 void MultiClass::dump() const {
1920 errs() << "Record:\n";
1923 errs() << "Defs:\n";
1924 for (const auto &Proto : DefPrototypes) {
1930 void RecordKeeper::dump() const { errs() << *this; }
1932 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1933 OS << "------------- Classes -----------------\n";
1934 const auto &Classes = RK.getClasses();
1935 for (const auto &C : Classes)
1936 OS << "class " << *C.second;
1938 OS << "------------- Defs -----------------\n";
1939 const auto &Defs = RK.getDefs();
1940 for (const auto &D : Defs)
1941 OS << "def " << *D.second;
1946 /// getAllDerivedDefinitions - This method returns all concrete definitions
1947 /// that derive from the specified class name. If a class with the specified
1948 /// name does not exist, an error is printed and true is returned.
1949 std::vector<Record*>
1950 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
1951 Record *Class = getClass(ClassName);
1953 PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
1955 std::vector<Record*> Defs;
1956 for (const auto &D : getDefs())
1957 if (D.second->isSubClassOf(Class))
1958 Defs.push_back(D.second.get());
1963 /// QualifyName - Return an Init with a qualifier prefix referring
1964 /// to CurRec's name.
1965 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1966 Init *Name, const std::string &Scoper) {
1967 RecTy *Type = cast<TypedInit>(Name)->getType();
1969 BinOpInit *NewName =
1970 BinOpInit::get(BinOpInit::STRCONCAT,
1971 BinOpInit::get(BinOpInit::STRCONCAT,
1972 CurRec.getNameInit(),
1973 StringInit::get(Scoper),
1974 Type)->Fold(&CurRec, CurMultiClass),
1978 if (CurMultiClass && Scoper != "::") {
1980 BinOpInit::get(BinOpInit::STRCONCAT,
1981 BinOpInit::get(BinOpInit::STRCONCAT,
1982 CurMultiClass->Rec.getNameInit(),
1983 StringInit::get("::"),
1984 Type)->Fold(&CurRec, CurMultiClass),
1985 NewName->Fold(&CurRec, CurMultiClass),
1989 return NewName->Fold(&CurRec, CurMultiClass);
1992 /// QualifyName - Return an Init with a qualifier prefix referring
1993 /// to CurRec's name.
1994 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1995 const std::string &Name,
1996 const std::string &Scoper) {
1997 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);