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 = 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<BitsRecTy*> Shared;
145 if (Sz >= Shared.size())
146 Shared.resize(Sz + 1);
147 BitsRecTy *&Ty = Shared[Sz];
149 Ty = 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 (ArrayRef<Init *>::iterator i = Range.begin(),
453 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
454 typedef FoldingSet<BitsInit> Pool;
458 ProfileBitsInit(ID, Range);
461 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
464 BitsInit *I = new BitsInit(Range);
465 ThePool.InsertNode(I, IP);
470 void BitsInit::Profile(FoldingSetNodeID &ID) const {
471 ProfileBitsInit(ID, Bits);
475 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
476 SmallVector<Init *, 16> NewBits(Bits.size());
478 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
479 if (Bits[i] >= getNumBits())
481 NewBits[i] = getBit(Bits[i]);
483 return BitsInit::get(NewBits);
486 std::string BitsInit::getAsString() const {
487 std::string Result = "{ ";
488 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
489 if (i) Result += ", ";
490 if (Init *Bit = getBit(e-i-1))
491 Result += Bit->getAsString();
495 return Result + " }";
498 // Fix bit initializer to preserve the behavior that bit reference from a unset
499 // bits initializer will resolve into VarBitInit to keep the field name and bit
500 // number used in targets with fixed insn length.
501 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
502 if (RV || !isa<UnsetInit>(After))
507 // resolveReferences - If there are any field references that refer to fields
508 // that have been filled in, we can propagate the values now.
510 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
511 bool Changed = false;
512 SmallVector<Init *, 16> NewBits(getNumBits());
514 Init *CachedInit = nullptr;
515 Init *CachedBitVar = nullptr;
516 bool CachedBitVarChanged = false;
518 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
519 Init *CurBit = Bits[i];
520 Init *CurBitVar = CurBit->getBitVar();
524 if (CurBitVar == CachedBitVar) {
525 if (CachedBitVarChanged) {
526 Init *Bit = CachedInit->getBit(CurBit->getBitNum());
527 NewBits[i] = fixBitInit(RV, CurBit, Bit);
531 CachedBitVar = CurBitVar;
532 CachedBitVarChanged = false;
537 CurBitVar = CurBitVar->resolveReferences(R, RV);
538 CachedBitVarChanged |= B != CurBitVar;
539 Changed |= B != CurBitVar;
540 } while (B != CurBitVar);
541 CachedInit = CurBitVar;
543 if (CachedBitVarChanged) {
544 Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
545 NewBits[i] = fixBitInit(RV, CurBit, Bit);
550 return BitsInit::get(NewBits);
552 return const_cast<BitsInit *>(this);
555 IntInit *IntInit::get(int64_t V) {
556 static DenseMap<int64_t, std::unique_ptr<IntInit>> ThePool;
558 std::unique_ptr<IntInit> &I = ThePool[V];
559 if (!I) I.reset(new IntInit(V));
563 std::string IntInit::getAsString() const {
564 return itostr(Value);
568 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
569 SmallVector<Init *, 16> NewBits(Bits.size());
571 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
575 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
577 return BitsInit::get(NewBits);
580 void StringInit::anchor() { }
582 StringInit *StringInit::get(StringRef V) {
583 static StringMap<std::unique_ptr<StringInit>> ThePool;
585 std::unique_ptr<StringInit> &I = ThePool[V];
586 if (!I) I.reset(new StringInit(V));
590 static void ProfileListInit(FoldingSetNodeID &ID,
591 ArrayRef<Init *> Range,
593 ID.AddInteger(Range.size());
594 ID.AddPointer(EltTy);
596 for (ArrayRef<Init *>::iterator i = Range.begin(),
603 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
604 typedef FoldingSet<ListInit> Pool;
606 static std::vector<std::unique_ptr<ListInit>> TheActualPool;
609 ProfileListInit(ID, Range, EltTy);
612 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
615 ListInit *I = new ListInit(Range, EltTy);
616 ThePool.InsertNode(I, IP);
617 TheActualPool.push_back(std::unique_ptr<ListInit>(I));
621 void ListInit::Profile(FoldingSetNodeID &ID) const {
622 ListRecTy *ListType = dyn_cast<ListRecTy>(getType());
623 assert(ListType && "Bad type for ListInit!");
624 RecTy *EltTy = ListType->getElementType();
626 ProfileListInit(ID, Values, EltTy);
630 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
631 std::vector<Init*> Vals;
632 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
633 if (Elements[i] >= getSize())
635 Vals.push_back(getElement(Elements[i]));
637 return ListInit::get(Vals, getType());
640 Record *ListInit::getElementAsRecord(unsigned i) const {
641 assert(i < Values.size() && "List element index out of range!");
642 DefInit *DI = dyn_cast<DefInit>(Values[i]);
644 PrintFatalError("Expected record in list!");
648 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
649 std::vector<Init*> Resolved;
650 Resolved.reserve(getSize());
651 bool Changed = false;
653 for (unsigned i = 0, e = getSize(); i != e; ++i) {
655 Init *CurElt = getElement(i);
659 CurElt = CurElt->resolveReferences(R, RV);
660 Changed |= E != CurElt;
661 } while (E != CurElt);
662 Resolved.push_back(E);
666 return ListInit::get(Resolved, getType());
667 return const_cast<ListInit *>(this);
670 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
671 unsigned Elt) const {
672 if (Elt >= getSize())
673 return nullptr; // Out of range reference.
674 Init *E = getElement(Elt);
675 // If the element is set to some value, or if we are resolving a reference
676 // to a specific variable and that variable is explicitly unset, then
677 // replace the VarListElementInit with it.
678 if (IRV || !isa<UnsetInit>(E))
683 std::string ListInit::getAsString() const {
684 std::string Result = "[";
685 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
686 if (i) Result += ", ";
687 Result += Values[i]->getAsString();
692 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
693 unsigned Elt) const {
694 Init *Resolved = resolveReferences(R, IRV);
695 OpInit *OResolved = dyn_cast<OpInit>(Resolved);
697 Resolved = OResolved->Fold(&R, nullptr);
700 if (Resolved != this) {
701 TypedInit *Typed = dyn_cast<TypedInit>(Resolved);
702 assert(Typed && "Expected typed init for list reference");
704 Init *New = Typed->resolveListElementReference(R, IRV, Elt);
707 return VarListElementInit::get(Typed, Elt);
714 Init *OpInit::getBit(unsigned Bit) const {
715 if (getType() == BitRecTy::get())
716 return const_cast<OpInit*>(this);
717 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
720 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
721 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
722 static DenseMap<Key, std::unique_ptr<UnOpInit>> ThePool;
724 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
726 std::unique_ptr<UnOpInit> &I = ThePool[TheKey];
727 if (!I) I.reset(new UnOpInit(opc, lhs, Type));
731 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
732 switch (getOpcode()) {
734 if (getType()->getAsString() == "string") {
735 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
738 if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
739 return StringInit::get(LHSd->getDef()->getName());
741 if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
742 return StringInit::get(LHSi->getAsString());
744 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
745 std::string Name = LHSs->getValue();
747 // From TGParser::ParseIDValue
749 if (const RecordVal *RV = CurRec->getValue(Name)) {
750 if (RV->getType() != getType())
751 PrintFatalError("type mismatch in cast");
752 return VarInit::get(Name, RV->getType());
755 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
758 if (CurRec->isTemplateArg(TemplateArgName)) {
759 const RecordVal *RV = CurRec->getValue(TemplateArgName);
760 assert(RV && "Template arg doesn't exist??");
762 if (RV->getType() != getType())
763 PrintFatalError("type mismatch in cast");
765 return VarInit::get(TemplateArgName, RV->getType());
770 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
772 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
773 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
774 assert(RV && "Template arg doesn't exist??");
776 if (RV->getType() != getType())
777 PrintFatalError("type mismatch in cast");
779 return VarInit::get(MCName, RV->getType());
782 assert(CurRec && "NULL pointer");
783 if (Record *D = (CurRec->getRecords()).getDef(Name))
784 return DefInit::get(D);
786 PrintFatalError(CurRec->getLoc(),
787 "Undefined reference:'" + Name + "'\n");
793 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
794 assert(LHSl->getSize() != 0 && "Empty list in car");
795 return LHSl->getElement(0);
800 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
801 assert(LHSl->getSize() != 0 && "Empty list in cdr");
802 // Note the +1. We can't just pass the result of getValues()
804 ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
805 ArrayRef<Init *>::iterator end = LHSl->getValues().end();
807 ListInit::get(ArrayRef<Init *>(begin, end - begin),
814 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
815 if (LHSl->getSize() == 0) {
816 return IntInit::get(1);
818 return IntInit::get(0);
821 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
822 if (LHSs->getValue().empty()) {
823 return IntInit::get(1);
825 return IntInit::get(0);
832 return const_cast<UnOpInit *>(this);
835 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
836 Init *lhs = LHS->resolveReferences(R, RV);
839 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, nullptr);
840 return Fold(&R, nullptr);
843 std::string UnOpInit::getAsString() const {
846 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
847 case HEAD: Result = "!head"; break;
848 case TAIL: Result = "!tail"; break;
849 case EMPTY: Result = "!empty"; break;
851 return Result + "(" + LHS->getAsString() + ")";
854 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
855 Init *rhs, RecTy *Type) {
857 std::pair<std::pair<unsigned, Init *>, Init *>,
861 static DenseMap<Key, std::unique_ptr<BinOpInit>> ThePool;
863 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
866 std::unique_ptr<BinOpInit> &I = ThePool[TheKey];
867 if (!I) I.reset(new BinOpInit(opc, lhs, rhs, Type));
871 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
872 switch (getOpcode()) {
874 DagInit *LHSs = dyn_cast<DagInit>(LHS);
875 DagInit *RHSs = dyn_cast<DagInit>(RHS);
877 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
878 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
879 if (!LOp || !ROp || LOp->getDef() != ROp->getDef())
880 PrintFatalError("Concated Dag operators do not match!");
881 std::vector<Init*> Args;
882 std::vector<std::string> ArgNames;
883 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
884 Args.push_back(LHSs->getArg(i));
885 ArgNames.push_back(LHSs->getArgName(i));
887 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
888 Args.push_back(RHSs->getArg(i));
889 ArgNames.push_back(RHSs->getArgName(i));
891 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
896 ListInit *LHSs = dyn_cast<ListInit>(LHS);
897 ListInit *RHSs = dyn_cast<ListInit>(RHS);
899 std::vector<Init *> Args;
900 Args.insert(Args.end(), LHSs->begin(), LHSs->end());
901 Args.insert(Args.end(), RHSs->begin(), RHSs->end());
902 return ListInit::get(
903 Args, static_cast<ListRecTy *>(LHSs->getType())->getElementType());
908 StringInit *LHSs = dyn_cast<StringInit>(LHS);
909 StringInit *RHSs = dyn_cast<StringInit>(RHS);
911 return StringInit::get(LHSs->getValue() + RHSs->getValue());
915 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
916 // to string objects.
918 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
920 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
923 return IntInit::get(L->getValue() == R->getValue());
925 StringInit *LHSs = dyn_cast<StringInit>(LHS);
926 StringInit *RHSs = dyn_cast<StringInit>(RHS);
928 // Make sure we've resolved
930 return IntInit::get(LHSs->getValue() == RHSs->getValue());
940 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
942 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
944 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
946 switch (getOpcode()) {
947 default: llvm_unreachable("Bad opcode!");
948 case ADD: Result = LHSv + RHSv; break;
949 case AND: Result = LHSv & RHSv; break;
950 case SHL: Result = LHSv << RHSv; break;
951 case SRA: Result = LHSv >> RHSv; break;
952 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
954 return IntInit::get(Result);
959 return const_cast<BinOpInit *>(this);
962 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
963 Init *lhs = LHS->resolveReferences(R, RV);
964 Init *rhs = RHS->resolveReferences(R, RV);
966 if (LHS != lhs || RHS != rhs)
967 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R,nullptr);
968 return Fold(&R, nullptr);
971 std::string BinOpInit::getAsString() const {
974 case CONCAT: Result = "!con"; break;
975 case ADD: Result = "!add"; break;
976 case AND: Result = "!and"; break;
977 case SHL: Result = "!shl"; break;
978 case SRA: Result = "!sra"; break;
979 case SRL: Result = "!srl"; break;
980 case EQ: Result = "!eq"; break;
981 case LISTCONCAT: Result = "!listconcat"; break;
982 case STRCONCAT: Result = "!strconcat"; break;
984 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
987 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs,
988 Init *mhs, Init *rhs,
992 std::pair<std::pair<unsigned, RecTy *>, Init *>,
998 typedef DenseMap<Key, TernOpInit *> Pool;
1001 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
1007 TernOpInit *&I = ThePool[TheKey];
1008 if (!I) I = new TernOpInit(opc, lhs, mhs, rhs, Type);
1012 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1013 Record *CurRec, MultiClass *CurMultiClass);
1015 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
1016 RecTy *Type, Record *CurRec,
1017 MultiClass *CurMultiClass) {
1018 std::vector<Init *> NewOperands;
1020 TypedInit *TArg = dyn_cast<TypedInit>(Arg);
1022 // If this is a dag, recurse
1023 if (TArg && TArg->getType()->getAsString() == "dag") {
1024 Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
1025 CurRec, CurMultiClass);
1029 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
1030 OpInit *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i));
1033 Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1034 Type, CurRec, CurMultiClass);
1036 NewOperands.push_back(Result);
1038 NewOperands.push_back(Arg);
1040 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1041 NewOperands.push_back(Arg);
1043 NewOperands.push_back(RHSo->getOperand(i));
1047 // Now run the operator and use its result as the new leaf
1048 const OpInit *NewOp = RHSo->clone(NewOperands);
1049 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
1050 return (NewVal != NewOp) ? NewVal : nullptr;
1053 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1054 Record *CurRec, MultiClass *CurMultiClass) {
1055 DagInit *MHSd = dyn_cast<DagInit>(MHS);
1056 ListInit *MHSl = dyn_cast<ListInit>(MHS);
1058 OpInit *RHSo = dyn_cast<OpInit>(RHS);
1061 PrintFatalError(CurRec->getLoc(), "!foreach requires an operator\n");
1064 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1067 PrintFatalError(CurRec->getLoc(), "!foreach requires typed variable\n");
1069 if ((MHSd && isa<DagRecTy>(Type)) || (MHSl && isa<ListRecTy>(Type))) {
1071 Init *Val = MHSd->getOperator();
1072 Init *Result = EvaluateOperation(RHSo, LHS, Val,
1073 Type, CurRec, CurMultiClass);
1078 std::vector<std::pair<Init *, std::string> > args;
1079 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1081 std::string ArgName;
1082 Arg = MHSd->getArg(i);
1083 ArgName = MHSd->getArgName(i);
1086 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1087 CurRec, CurMultiClass);
1092 // TODO: Process arg names
1093 args.push_back(std::make_pair(Arg, ArgName));
1096 return DagInit::get(Val, "", args);
1099 std::vector<Init *> NewOperands;
1100 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1102 for (std::vector<Init *>::iterator li = NewList.begin(),
1103 liend = NewList.end();
1107 NewOperands.clear();
1108 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1109 // First, replace the foreach variable with the list item
1110 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1111 NewOperands.push_back(Item);
1113 NewOperands.push_back(RHSo->getOperand(i));
1117 // Now run the operator and use its result as the new list item
1118 const OpInit *NewOp = RHSo->clone(NewOperands);
1119 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1120 if (NewItem != NewOp)
1123 return ListInit::get(NewList, MHSl->getType());
1129 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1130 switch (getOpcode()) {
1132 DefInit *LHSd = dyn_cast<DefInit>(LHS);
1133 VarInit *LHSv = dyn_cast<VarInit>(LHS);
1134 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1136 DefInit *MHSd = dyn_cast<DefInit>(MHS);
1137 VarInit *MHSv = dyn_cast<VarInit>(MHS);
1138 StringInit *MHSs = dyn_cast<StringInit>(MHS);
1140 DefInit *RHSd = dyn_cast<DefInit>(RHS);
1141 VarInit *RHSv = dyn_cast<VarInit>(RHS);
1142 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1144 if ((LHSd && MHSd && RHSd)
1145 || (LHSv && MHSv && RHSv)
1146 || (LHSs && MHSs && RHSs)) {
1148 Record *Val = RHSd->getDef();
1149 if (LHSd->getAsString() == RHSd->getAsString()) {
1150 Val = MHSd->getDef();
1152 return DefInit::get(Val);
1155 std::string Val = RHSv->getName();
1156 if (LHSv->getAsString() == RHSv->getAsString()) {
1157 Val = MHSv->getName();
1159 return VarInit::get(Val, getType());
1162 std::string Val = RHSs->getValue();
1164 std::string::size_type found;
1165 std::string::size_type idx = 0;
1167 found = Val.find(LHSs->getValue(), idx);
1168 if (found != std::string::npos) {
1169 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1171 idx = found + MHSs->getValue().size();
1172 } while (found != std::string::npos);
1174 return StringInit::get(Val);
1181 Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1182 CurRec, CurMultiClass);
1190 IntInit *LHSi = dyn_cast<IntInit>(LHS);
1191 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1192 LHSi = dyn_cast<IntInit>(I);
1194 if (LHSi->getValue()) {
1204 return const_cast<TernOpInit *>(this);
1207 Init *TernOpInit::resolveReferences(Record &R,
1208 const RecordVal *RV) const {
1209 Init *lhs = LHS->resolveReferences(R, RV);
1211 if (Opc == IF && lhs != LHS) {
1212 IntInit *Value = dyn_cast<IntInit>(lhs);
1213 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1214 Value = dyn_cast<IntInit>(I);
1217 if (Value->getValue()) {
1218 Init *mhs = MHS->resolveReferences(R, RV);
1219 return (TernOpInit::get(getOpcode(), lhs, mhs,
1220 RHS, getType()))->Fold(&R, nullptr);
1222 Init *rhs = RHS->resolveReferences(R, RV);
1223 return (TernOpInit::get(getOpcode(), lhs, MHS,
1224 rhs, getType()))->Fold(&R, nullptr);
1229 Init *mhs = MHS->resolveReferences(R, RV);
1230 Init *rhs = RHS->resolveReferences(R, RV);
1232 if (LHS != lhs || MHS != mhs || RHS != rhs)
1233 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1234 getType()))->Fold(&R, nullptr);
1235 return Fold(&R, nullptr);
1238 std::string TernOpInit::getAsString() const {
1241 case SUBST: Result = "!subst"; break;
1242 case FOREACH: Result = "!foreach"; break;
1243 case IF: Result = "!if"; break;
1245 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
1246 + RHS->getAsString() + ")";
1249 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1250 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
1251 if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
1252 return Field->getType();
1257 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1258 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1259 if (!T) return nullptr; // Cannot subscript a non-bits variable.
1260 unsigned NumBits = T->getNumBits();
1262 SmallVector<Init *, 16> NewBits(Bits.size());
1263 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1264 if (Bits[i] >= NumBits)
1267 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1269 return BitsInit::get(NewBits);
1273 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1274 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1275 if (!T) return nullptr; // Cannot subscript a non-list variable.
1277 if (Elements.size() == 1)
1278 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1280 std::vector<Init*> ListInits;
1281 ListInits.reserve(Elements.size());
1282 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1283 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1285 return ListInit::get(ListInits, T);
1289 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1290 Init *Value = StringInit::get(VN);
1291 return VarInit::get(Value, T);
1294 VarInit *VarInit::get(Init *VN, RecTy *T) {
1295 typedef std::pair<RecTy *, Init *> Key;
1296 static DenseMap<Key, std::unique_ptr<VarInit>> ThePool;
1298 Key TheKey(std::make_pair(T, VN));
1300 std::unique_ptr<VarInit> &I = ThePool[TheKey];
1301 if (!I) I.reset(new VarInit(VN, T));
1305 const std::string &VarInit::getName() const {
1306 StringInit *NameString = dyn_cast<StringInit>(getNameInit());
1307 assert(NameString && "VarInit name is not a string!");
1308 return NameString->getValue();
1311 Init *VarInit::getBit(unsigned Bit) const {
1312 if (getType() == BitRecTy::get())
1313 return const_cast<VarInit*>(this);
1314 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1317 Init *VarInit::resolveListElementReference(Record &R,
1318 const RecordVal *IRV,
1319 unsigned Elt) const {
1320 if (R.isTemplateArg(getNameInit())) return nullptr;
1321 if (IRV && IRV->getNameInit() != getNameInit()) return nullptr;
1323 RecordVal *RV = R.getValue(getNameInit());
1324 assert(RV && "Reference to a non-existent variable?");
1325 ListInit *LI = dyn_cast<ListInit>(RV->getValue());
1327 TypedInit *VI = dyn_cast<TypedInit>(RV->getValue());
1328 assert(VI && "Invalid list element!");
1329 return VarListElementInit::get(VI, Elt);
1332 if (Elt >= LI->getSize())
1333 return nullptr; // Out of range reference.
1334 Init *E = LI->getElement(Elt);
1335 // If the element is set to some value, or if we are resolving a reference
1336 // to a specific variable and that variable is explicitly unset, then
1337 // replace the VarListElementInit with it.
1338 if (IRV || !isa<UnsetInit>(E))
1344 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1345 if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
1346 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1347 return RV->getType();
1351 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1352 const std::string &FieldName) const {
1353 if (isa<RecordRecTy>(getType()))
1354 if (const RecordVal *Val = R.getValue(VarName)) {
1355 if (RV != Val && (RV || isa<UnsetInit>(Val->getValue())))
1357 Init *TheInit = Val->getValue();
1358 assert(TheInit != this && "Infinite loop detected!");
1359 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1367 /// resolveReferences - This method is used by classes that refer to other
1368 /// variables which may not be defined at the time the expression is formed.
1369 /// If a value is set for the variable later, this method will be called on
1370 /// users of the value to allow the value to propagate out.
1372 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1373 if (RecordVal *Val = R.getValue(VarName))
1374 if (RV == Val || (!RV && !isa<UnsetInit>(Val->getValue())))
1375 return Val->getValue();
1376 return const_cast<VarInit *>(this);
1379 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1380 typedef std::pair<TypedInit *, unsigned> Key;
1381 static DenseMap<Key, std::unique_ptr<VarBitInit>> ThePool;
1383 Key TheKey(std::make_pair(T, B));
1385 std::unique_ptr<VarBitInit> &I = ThePool[TheKey];
1386 if (!I) I.reset(new VarBitInit(T, B));
1390 std::string VarBitInit::getAsString() const {
1391 return TI->getAsString() + "{" + utostr(Bit) + "}";
1394 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1395 Init *I = TI->resolveReferences(R, RV);
1397 return I->getBit(getBitNum());
1399 return const_cast<VarBitInit*>(this);
1402 VarListElementInit *VarListElementInit::get(TypedInit *T,
1404 typedef std::pair<TypedInit *, unsigned> Key;
1405 typedef DenseMap<Key, VarListElementInit *> Pool;
1407 static Pool ThePool;
1409 Key TheKey(std::make_pair(T, E));
1411 VarListElementInit *&I = ThePool[TheKey];
1412 if (!I) I = new VarListElementInit(T, E);
1416 std::string VarListElementInit::getAsString() const {
1417 return TI->getAsString() + "[" + utostr(Element) + "]";
1421 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1422 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1425 return const_cast<VarListElementInit *>(this);
1428 Init *VarListElementInit::getBit(unsigned Bit) const {
1429 if (getType() == BitRecTy::get())
1430 return const_cast<VarListElementInit*>(this);
1431 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1434 Init *VarListElementInit:: resolveListElementReference(Record &R,
1435 const RecordVal *RV,
1436 unsigned Elt) const {
1437 Init *Result = TI->resolveListElementReference(R, RV, Element);
1440 if (TypedInit *TInit = dyn_cast<TypedInit>(Result)) {
1441 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1442 if (Result2) return Result2;
1443 return new VarListElementInit(TInit, Elt);
1451 DefInit *DefInit::get(Record *R) {
1452 return R->getDefInit();
1455 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1456 if (const RecordVal *RV = Def->getValue(FieldName))
1457 return RV->getType();
1461 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1462 const std::string &FieldName) const {
1463 return Def->getValue(FieldName)->getValue();
1467 std::string DefInit::getAsString() const {
1468 return Def->getName();
1471 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1472 typedef std::pair<Init *, TableGenStringKey> Key;
1473 typedef DenseMap<Key, FieldInit *> Pool;
1474 static Pool ThePool;
1476 Key TheKey(std::make_pair(R, FN));
1478 FieldInit *&I = ThePool[TheKey];
1479 if (!I) I = new FieldInit(R, FN);
1483 Init *FieldInit::getBit(unsigned Bit) const {
1484 if (getType() == BitRecTy::get())
1485 return const_cast<FieldInit*>(this);
1486 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1489 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1490 unsigned Elt) const {
1491 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1492 if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
1493 if (Elt >= LI->getSize()) return nullptr;
1494 Init *E = LI->getElement(Elt);
1496 // If the element is set to some value, or if we are resolving a
1497 // reference to a specific variable and that variable is explicitly
1498 // unset, then replace the VarListElementInit with it.
1499 if (RV || !isa<UnsetInit>(E))
1505 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1506 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1508 Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1510 Init *BVR = BitsVal->resolveReferences(R, RV);
1511 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1514 if (NewRec != Rec) {
1515 return FieldInit::get(NewRec, FieldName);
1517 return const_cast<FieldInit *>(this);
1520 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, const std::string &VN,
1521 ArrayRef<Init *> ArgRange,
1522 ArrayRef<std::string> NameRange) {
1526 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1527 ArrayRef<std::string>::iterator Name = NameRange.begin();
1528 while (Arg != ArgRange.end()) {
1529 assert(Name != NameRange.end() && "Arg name underflow!");
1530 ID.AddPointer(*Arg++);
1531 ID.AddString(*Name++);
1533 assert(Name == NameRange.end() && "Arg name overflow!");
1537 DagInit::get(Init *V, const std::string &VN,
1538 ArrayRef<Init *> ArgRange,
1539 ArrayRef<std::string> NameRange) {
1540 typedef FoldingSet<DagInit> Pool;
1541 static Pool ThePool;
1543 FoldingSetNodeID ID;
1544 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1547 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1550 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1551 ThePool.InsertNode(I, IP);
1557 DagInit::get(Init *V, const std::string &VN,
1558 const std::vector<std::pair<Init*, std::string> > &args) {
1559 typedef std::pair<Init*, std::string> PairType;
1561 std::vector<Init *> Args;
1562 std::vector<std::string> Names;
1564 for (std::vector<PairType>::const_iterator i = args.begin(),
1568 Args.push_back(i->first);
1569 Names.push_back(i->second);
1572 return DagInit::get(V, VN, Args, Names);
1575 void DagInit::Profile(FoldingSetNodeID &ID) const {
1576 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1579 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1580 std::vector<Init*> NewArgs;
1581 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1582 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1584 Init *Op = Val->resolveReferences(R, RV);
1586 if (Args != NewArgs || Op != Val)
1587 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1589 return const_cast<DagInit *>(this);
1593 std::string DagInit::getAsString() const {
1594 std::string Result = "(" + Val->getAsString();
1595 if (!ValName.empty())
1596 Result += ":" + ValName;
1597 if (!Args.empty()) {
1598 Result += " " + Args[0]->getAsString();
1599 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1600 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1601 Result += ", " + Args[i]->getAsString();
1602 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1605 return Result + ")";
1609 //===----------------------------------------------------------------------===//
1610 // Other implementations
1611 //===----------------------------------------------------------------------===//
1613 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1614 : Name(N), Ty(T), Prefix(P) {
1615 Value = Ty->convertValue(UnsetInit::get());
1616 assert(Value && "Cannot create unset value for current type!");
1619 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1620 : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1621 Value = Ty->convertValue(UnsetInit::get());
1622 assert(Value && "Cannot create unset value for current type!");
1625 const std::string &RecordVal::getName() const {
1626 StringInit *NameString = dyn_cast<StringInit>(Name);
1627 assert(NameString && "RecordVal name is not a string!");
1628 return NameString->getValue();
1631 void RecordVal::dump() const { errs() << *this; }
1633 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1634 if (getPrefix()) OS << "field ";
1635 OS << *getType() << " " << getNameInitAsString();
1638 OS << " = " << *getValue();
1640 if (PrintSem) OS << ";\n";
1643 unsigned Record::LastID = 0;
1645 void Record::init() {
1648 // Every record potentially has a def at the top. This value is
1649 // replaced with the top-level def name at instantiation time.
1650 RecordVal DN("NAME", StringRecTy::get(), 0);
1654 void Record::checkName() {
1655 // Ensure the record name has string type.
1656 const TypedInit *TypedName = dyn_cast<const TypedInit>(Name);
1657 assert(TypedName && "Record name is not typed!");
1658 RecTy *Type = TypedName->getType();
1659 if (!isa<StringRecTy>(Type))
1660 PrintFatalError(getLoc(), "Record name is not a string!");
1663 DefInit *Record::getDefInit() {
1665 TheInit = new DefInit(this, new RecordRecTy(this));
1669 const std::string &Record::getName() const {
1670 const StringInit *NameString = dyn_cast<StringInit>(Name);
1671 assert(NameString && "Record name is not a string!");
1672 return NameString->getValue();
1675 void Record::setName(Init *NewName) {
1678 // DO NOT resolve record values to the name at this point because
1679 // there might be default values for arguments of this def. Those
1680 // arguments might not have been resolved yet so we don't want to
1681 // prematurely assume values for those arguments were not passed to
1684 // Nonetheless, it may be that some of this Record's values
1685 // reference the record name. Indeed, the reason for having the
1686 // record name be an Init is to provide this flexibility. The extra
1687 // resolve steps after completely instantiating defs takes care of
1688 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1691 void Record::setName(const std::string &Name) {
1692 setName(StringInit::get(Name));
1695 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1696 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1698 void Record::resolveReferencesTo(const RecordVal *RV) {
1699 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1700 if (RV == &Values[i]) // Skip resolve the same field as the given one
1702 if (Init *V = Values[i].getValue())
1703 if (Values[i].setValue(V->resolveReferences(*this, RV)))
1704 PrintFatalError(getLoc(), "Invalid value is found when setting '"
1705 + Values[i].getNameInitAsString()
1706 + "' after resolving references"
1707 + (RV ? " against '" + RV->getNameInitAsString()
1709 + RV->getValue()->getAsUnquotedString() + ")"
1713 Init *OldName = getNameInit();
1714 Init *NewName = Name->resolveReferences(*this, RV);
1715 if (NewName != OldName) {
1716 // Re-register with RecordKeeper.
1721 void Record::dump() const { errs() << *this; }
1723 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1724 OS << R.getNameInitAsString();
1726 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1727 if (!TArgs.empty()) {
1729 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1731 const RecordVal *RV = R.getValue(TArgs[i]);
1732 assert(RV && "Template argument record not found??");
1733 RV->print(OS, false);
1739 const std::vector<Record*> &SC = R.getSuperClasses();
1742 for (unsigned i = 0, e = SC.size(); i != e; ++i)
1743 OS << " " << SC[i]->getNameInitAsString();
1747 const std::vector<RecordVal> &Vals = R.getValues();
1748 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1749 if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1751 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1752 if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1758 /// getValueInit - Return the initializer for a value with the specified name,
1759 /// or abort if the field does not exist.
1761 Init *Record::getValueInit(StringRef FieldName) const {
1762 const RecordVal *R = getValue(FieldName);
1763 if (!R || !R->getValue())
1764 PrintFatalError(getLoc(), "Record `" + getName() +
1765 "' does not have a field named `" + FieldName + "'!\n");
1766 return R->getValue();
1770 /// getValueAsString - This method looks up the specified field and returns its
1771 /// value as a string, aborts if the field does not exist or if
1772 /// the value is not a string.
1774 std::string Record::getValueAsString(StringRef FieldName) const {
1775 const RecordVal *R = getValue(FieldName);
1776 if (!R || !R->getValue())
1777 PrintFatalError(getLoc(), "Record `" + getName() +
1778 "' does not have a field named `" + FieldName + "'!\n");
1780 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1781 return SI->getValue();
1782 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1783 FieldName + "' does not have a string initializer!");
1786 /// getValueAsBitsInit - This method looks up the specified field and returns
1787 /// its value as a BitsInit, aborts if the field does not exist or if
1788 /// the value is not the right type.
1790 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1791 const RecordVal *R = getValue(FieldName);
1792 if (!R || !R->getValue())
1793 PrintFatalError(getLoc(), "Record `" + getName() +
1794 "' does not have a field named `" + FieldName + "'!\n");
1796 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
1798 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1799 FieldName + "' does not have a BitsInit initializer!");
1802 /// getValueAsListInit - This method looks up the specified field and returns
1803 /// its value as a ListInit, aborting if the field does not exist or if
1804 /// the value is not the right type.
1806 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1807 const RecordVal *R = getValue(FieldName);
1808 if (!R || !R->getValue())
1809 PrintFatalError(getLoc(), "Record `" + getName() +
1810 "' does not have a field named `" + FieldName + "'!\n");
1812 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
1814 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1815 FieldName + "' does not have a list initializer!");
1818 /// getValueAsListOfDefs - This method looks up the specified field and returns
1819 /// its value as a vector of records, aborting if the field does not exist
1820 /// or if the value is not the right type.
1822 std::vector<Record*>
1823 Record::getValueAsListOfDefs(StringRef FieldName) const {
1824 ListInit *List = getValueAsListInit(FieldName);
1825 std::vector<Record*> Defs;
1826 for (unsigned i = 0; i < List->getSize(); i++) {
1827 if (DefInit *DI = dyn_cast<DefInit>(List->getElement(i))) {
1828 Defs.push_back(DI->getDef());
1830 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1831 FieldName + "' list is not entirely DefInit!");
1837 /// getValueAsInt - This method looks up the specified field and returns its
1838 /// value as an int64_t, aborting if the field does not exist or if the value
1839 /// is not the right type.
1841 int64_t Record::getValueAsInt(StringRef FieldName) const {
1842 const RecordVal *R = getValue(FieldName);
1843 if (!R || !R->getValue())
1844 PrintFatalError(getLoc(), "Record `" + getName() +
1845 "' does not have a field named `" + FieldName + "'!\n");
1847 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
1848 return II->getValue();
1849 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1850 FieldName + "' does not have an int initializer!");
1853 /// getValueAsListOfInts - This method looks up the specified field and returns
1854 /// its value as a vector of integers, aborting if the field does not exist or
1855 /// if the value is not the right type.
1857 std::vector<int64_t>
1858 Record::getValueAsListOfInts(StringRef FieldName) const {
1859 ListInit *List = getValueAsListInit(FieldName);
1860 std::vector<int64_t> Ints;
1861 for (unsigned i = 0; i < List->getSize(); i++) {
1862 if (IntInit *II = dyn_cast<IntInit>(List->getElement(i))) {
1863 Ints.push_back(II->getValue());
1865 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1866 FieldName + "' does not have a list of ints initializer!");
1872 /// getValueAsListOfStrings - This method looks up the specified field and
1873 /// returns its value as a vector of strings, aborting if the field does not
1874 /// exist or if the value is not the right type.
1876 std::vector<std::string>
1877 Record::getValueAsListOfStrings(StringRef FieldName) const {
1878 ListInit *List = getValueAsListInit(FieldName);
1879 std::vector<std::string> Strings;
1880 for (unsigned i = 0; i < List->getSize(); i++) {
1881 if (StringInit *II = dyn_cast<StringInit>(List->getElement(i))) {
1882 Strings.push_back(II->getValue());
1884 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1885 FieldName + "' does not have a list of strings initializer!");
1891 /// getValueAsDef - This method looks up the specified field and returns its
1892 /// value as a Record, aborting if the field does not exist or if the value
1893 /// is not the right type.
1895 Record *Record::getValueAsDef(StringRef FieldName) const {
1896 const RecordVal *R = getValue(FieldName);
1897 if (!R || !R->getValue())
1898 PrintFatalError(getLoc(), "Record `" + getName() +
1899 "' does not have a field named `" + FieldName + "'!\n");
1901 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
1902 return DI->getDef();
1903 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1904 FieldName + "' does not have a def initializer!");
1907 /// getValueAsBit - This method looks up the specified field and returns its
1908 /// value as a bit, aborting if the field does not exist or if the value is
1909 /// not the right type.
1911 bool Record::getValueAsBit(StringRef FieldName) const {
1912 const RecordVal *R = getValue(FieldName);
1913 if (!R || !R->getValue())
1914 PrintFatalError(getLoc(), "Record `" + getName() +
1915 "' does not have a field named `" + FieldName + "'!\n");
1917 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1918 return BI->getValue();
1919 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1920 FieldName + "' does not have a bit initializer!");
1923 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1924 const RecordVal *R = getValue(FieldName);
1925 if (!R || !R->getValue())
1926 PrintFatalError(getLoc(), "Record `" + getName() +
1927 "' does not have a field named `" + FieldName.str() + "'!\n");
1929 if (isa<UnsetInit>(R->getValue())) {
1934 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1935 return BI->getValue();
1936 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1937 FieldName + "' does not have a bit initializer!");
1940 /// getValueAsDag - This method looks up the specified field and returns its
1941 /// value as an Dag, aborting if the field does not exist or if the value is
1942 /// not the right type.
1944 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1945 const RecordVal *R = getValue(FieldName);
1946 if (!R || !R->getValue())
1947 PrintFatalError(getLoc(), "Record `" + getName() +
1948 "' does not have a field named `" + FieldName + "'!\n");
1950 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
1952 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1953 FieldName + "' does not have a dag initializer!");
1957 void MultiClass::dump() const {
1958 errs() << "Record:\n";
1961 errs() << "Defs:\n";
1962 for (RecordVector::const_iterator r = DefPrototypes.begin(),
1963 rend = DefPrototypes.end();
1971 void RecordKeeper::dump() const { errs() << *this; }
1973 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1974 OS << "------------- Classes -----------------\n";
1975 const auto &Classes = RK.getClasses();
1976 for (const auto &C : Classes)
1977 OS << "class " << *C.second;
1979 OS << "------------- Defs -----------------\n";
1980 const auto &Defs = RK.getDefs();
1981 for (const auto &D : Defs)
1982 OS << "def " << *D.second;
1987 /// getAllDerivedDefinitions - This method returns all concrete definitions
1988 /// that derive from the specified class name. If a class with the specified
1989 /// name does not exist, an error is printed and true is returned.
1990 std::vector<Record*>
1991 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
1992 Record *Class = getClass(ClassName);
1994 PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
1996 std::vector<Record*> Defs;
1997 for (const auto &D : getDefs())
1998 if (D.second->isSubClassOf(Class))
1999 Defs.push_back(D.second.get());
2004 /// QualifyName - Return an Init with a qualifier prefix referring
2005 /// to CurRec's name.
2006 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2007 Init *Name, const std::string &Scoper) {
2008 RecTy *Type = cast<TypedInit>(Name)->getType();
2010 BinOpInit *NewName =
2011 BinOpInit::get(BinOpInit::STRCONCAT,
2012 BinOpInit::get(BinOpInit::STRCONCAT,
2013 CurRec.getNameInit(),
2014 StringInit::get(Scoper),
2015 Type)->Fold(&CurRec, CurMultiClass),
2019 if (CurMultiClass && Scoper != "::") {
2021 BinOpInit::get(BinOpInit::STRCONCAT,
2022 BinOpInit::get(BinOpInit::STRCONCAT,
2023 CurMultiClass->Rec.getNameInit(),
2024 StringInit::get("::"),
2025 Type)->Fold(&CurRec, CurMultiClass),
2026 NewName->Fold(&CurRec, CurMultiClass),
2030 return NewName->Fold(&CurRec, CurMultiClass);
2033 /// QualifyName - Return an Init with a qualifier prefix referring
2034 /// to CurRec's name.
2035 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2036 const std::string &Name,
2037 const std::string &Scoper) {
2038 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);