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::dump() const { print(errs()); }
91 ListRecTy *RecTy::getListTy() {
93 ListTy.reset(new ListRecTy(this));
97 bool RecTy::typeIsConvertibleTo(const RecTy *RHS) const {
98 assert(RHS && "NULL pointer");
99 return Kind == RHS->getRecTyKind();
102 bool BitRecTy::typeIsConvertibleTo(const RecTy *RHS) const{
103 if(RecTy::typeIsConvertibleTo(RHS) || RHS->getRecTyKind() == IntRecTyKind)
105 if(const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
106 return BitsTy->getNumBits() == 1;
110 BitsRecTy *BitsRecTy::get(unsigned Sz) {
111 static std::vector<std::unique_ptr<BitsRecTy>> Shared;
112 if (Sz >= Shared.size())
113 Shared.resize(Sz + 1);
114 std::unique_ptr<BitsRecTy> &Ty = Shared[Sz];
116 Ty.reset(new BitsRecTy(Sz));
120 std::string BitsRecTy::getAsString() const {
121 return "bits<" + utostr(Size) + ">";
124 bool BitsRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
125 if (RecTy::typeIsConvertibleTo(RHS)) //argument and the sender are same type
126 return cast<BitsRecTy>(RHS)->Size == Size;
127 RecTyKind kind = RHS->getRecTyKind();
128 return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
131 bool IntRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
132 RecTyKind kind = RHS->getRecTyKind();
133 return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
136 std::string StringRecTy::getAsString() const {
140 std::string ListRecTy::getAsString() const {
141 return "list<" + Ty->getAsString() + ">";
144 bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
145 if (const auto *ListTy = dyn_cast<ListRecTy>(RHS))
146 return Ty->typeIsConvertibleTo(ListTy->getElementType());
150 std::string DagRecTy::getAsString() const {
154 RecordRecTy *RecordRecTy::get(Record *R) {
155 return dyn_cast<RecordRecTy>(R->getDefInit()->getType());
158 std::string RecordRecTy::getAsString() const {
159 return Rec->getName();
162 bool RecordRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
163 const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
167 if (RTy->getRecord() == Rec || Rec->isSubClassOf(RTy->getRecord()))
170 for (Record *SC : RTy->getRecord()->getSuperClasses())
171 if (Rec->isSubClassOf(SC))
177 /// resolveTypes - Find a common type that T1 and T2 convert to.
178 /// Return null if no such type exists.
180 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
181 if (T1->typeIsConvertibleTo(T2))
183 if (T2->typeIsConvertibleTo(T1))
186 // If one is a Record type, check superclasses
187 if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
188 // See if T2 inherits from a type T1 also inherits from
189 for (Record *SuperRec1 : RecTy1->getRecord()->getSuperClasses()) {
190 RecordRecTy *SuperRecTy1 = RecordRecTy::get(SuperRec1);
191 RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
196 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) {
197 // See if T1 inherits from a type T2 also inherits from
198 for (Record *SuperRec2 : RecTy2->getRecord()->getSuperClasses()) {
199 RecordRecTy *SuperRecTy2 = RecordRecTy::get(SuperRec2);
200 RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
209 //===----------------------------------------------------------------------===//
210 // Initializer implementations
211 //===----------------------------------------------------------------------===//
213 void Init::anchor() { }
214 void Init::dump() const { return print(errs()); }
216 UnsetInit *UnsetInit::get() {
217 static UnsetInit TheInit;
221 Init *UnsetInit::convertInitializerTo(RecTy *Ty) const {
222 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
223 SmallVector<Init *, 16> NewBits(BRT->getNumBits());
225 for (unsigned i = 0; i != BRT->getNumBits(); ++i)
226 NewBits[i] = UnsetInit::get();
228 return BitsInit::get(NewBits);
231 // All other types can just be returned.
232 return const_cast<UnsetInit *>(this);
235 BitInit *BitInit::get(bool V) {
236 static BitInit True(true);
237 static BitInit False(false);
239 return V ? &True : &False;
242 Init *BitInit::convertInitializerTo(RecTy *Ty) const {
243 if (isa<BitRecTy>(Ty))
244 return const_cast<BitInit *>(this);
246 if (isa<IntRecTy>(Ty))
247 return IntInit::get(getValue());
249 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
250 // Can only convert single bit.
251 if (BRT->getNumBits() == 1)
252 return BitsInit::get(const_cast<BitInit *>(this));
259 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
260 ID.AddInteger(Range.size());
262 for (Init *I : Range)
266 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
267 static FoldingSet<BitsInit> ThePool;
268 static std::vector<std::unique_ptr<BitsInit>> TheActualPool;
271 ProfileBitsInit(ID, Range);
274 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
277 BitsInit *I = new BitsInit(Range);
278 ThePool.InsertNode(I, IP);
279 TheActualPool.push_back(std::unique_ptr<BitsInit>(I));
283 void BitsInit::Profile(FoldingSetNodeID &ID) const {
284 ProfileBitsInit(ID, Bits);
287 Init *BitsInit::convertInitializerTo(RecTy *Ty) const {
288 if (isa<BitRecTy>(Ty)) {
289 if (getNumBits() != 1) return nullptr; // Only accept if just one bit!
293 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
294 // If the number of bits is right, return it. Otherwise we need to expand
296 if (getNumBits() != BRT->getNumBits()) return nullptr;
297 return const_cast<BitsInit *>(this);
300 if (isa<IntRecTy>(Ty)) {
302 for (unsigned i = 0, e = getNumBits(); i != e; ++i)
303 if (auto *Bit = dyn_cast<BitInit>(getBit(i)))
304 Result |= static_cast<int64_t>(Bit->getValue()) << i;
307 return IntInit::get(Result);
314 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
315 SmallVector<Init *, 16> NewBits(Bits.size());
317 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
318 if (Bits[i] >= getNumBits())
320 NewBits[i] = getBit(Bits[i]);
322 return BitsInit::get(NewBits);
325 std::string BitsInit::getAsString() const {
326 std::string Result = "{ ";
327 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
328 if (i) Result += ", ";
329 if (Init *Bit = getBit(e-i-1))
330 Result += Bit->getAsString();
334 return Result + " }";
337 // Fix bit initializer to preserve the behavior that bit reference from a unset
338 // bits initializer will resolve into VarBitInit to keep the field name and bit
339 // number used in targets with fixed insn length.
340 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
341 if (RV || !isa<UnsetInit>(After))
346 // resolveReferences - If there are any field references that refer to fields
347 // that have been filled in, we can propagate the values now.
349 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
350 bool Changed = false;
351 SmallVector<Init *, 16> NewBits(getNumBits());
353 Init *CachedInit = nullptr;
354 Init *CachedBitVar = nullptr;
355 bool CachedBitVarChanged = false;
357 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
358 Init *CurBit = Bits[i];
359 Init *CurBitVar = CurBit->getBitVar();
363 if (CurBitVar == CachedBitVar) {
364 if (CachedBitVarChanged) {
365 Init *Bit = CachedInit->getBit(CurBit->getBitNum());
366 NewBits[i] = fixBitInit(RV, CurBit, Bit);
370 CachedBitVar = CurBitVar;
371 CachedBitVarChanged = false;
376 CurBitVar = CurBitVar->resolveReferences(R, RV);
377 CachedBitVarChanged |= B != CurBitVar;
378 Changed |= B != CurBitVar;
379 } while (B != CurBitVar);
380 CachedInit = CurBitVar;
382 if (CachedBitVarChanged) {
383 Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
384 NewBits[i] = fixBitInit(RV, CurBit, Bit);
389 return BitsInit::get(NewBits);
391 return const_cast<BitsInit *>(this);
394 IntInit *IntInit::get(int64_t V) {
395 static DenseMap<int64_t, std::unique_ptr<IntInit>> ThePool;
397 std::unique_ptr<IntInit> &I = ThePool[V];
398 if (!I) I.reset(new IntInit(V));
402 std::string IntInit::getAsString() const {
403 return itostr(Value);
406 /// canFitInBitfield - Return true if the number of bits is large enough to hold
407 /// the integer value.
408 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
409 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
410 return (NumBits >= sizeof(Value) * 8) ||
411 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
414 Init *IntInit::convertInitializerTo(RecTy *Ty) const {
415 if (isa<IntRecTy>(Ty))
416 return const_cast<IntInit *>(this);
418 if (isa<BitRecTy>(Ty)) {
419 int64_t Val = getValue();
420 if (Val != 0 && Val != 1) return nullptr; // Only accept 0 or 1 for a bit!
421 return BitInit::get(Val != 0);
424 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
425 int64_t Value = getValue();
426 // Make sure this bitfield is large enough to hold the integer value.
427 if (!canFitInBitfield(Value, BRT->getNumBits()))
430 SmallVector<Init *, 16> NewBits(BRT->getNumBits());
431 for (unsigned i = 0; i != BRT->getNumBits(); ++i)
432 NewBits[i] = BitInit::get(Value & (1LL << i));
434 return BitsInit::get(NewBits);
441 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
442 SmallVector<Init *, 16> NewBits(Bits.size());
444 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
448 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
450 return BitsInit::get(NewBits);
453 StringInit *StringInit::get(StringRef V) {
454 static StringMap<std::unique_ptr<StringInit>> ThePool;
456 std::unique_ptr<StringInit> &I = ThePool[V];
457 if (!I) I.reset(new StringInit(V));
461 Init *StringInit::convertInitializerTo(RecTy *Ty) const {
462 if (isa<StringRecTy>(Ty))
463 return const_cast<StringInit *>(this);
468 static void ProfileListInit(FoldingSetNodeID &ID,
469 ArrayRef<Init *> Range,
471 ID.AddInteger(Range.size());
472 ID.AddPointer(EltTy);
474 for (Init *I : Range)
478 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
479 static FoldingSet<ListInit> ThePool;
480 static std::vector<std::unique_ptr<ListInit>> TheActualPool;
483 ProfileListInit(ID, Range, EltTy);
486 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
489 ListInit *I = new ListInit(Range, EltTy);
490 ThePool.InsertNode(I, IP);
491 TheActualPool.push_back(std::unique_ptr<ListInit>(I));
495 void ListInit::Profile(FoldingSetNodeID &ID) const {
496 RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
498 ProfileListInit(ID, Values, EltTy);
501 Init *ListInit::convertInitializerTo(RecTy *Ty) const {
502 if (auto *LRT = dyn_cast<ListRecTy>(Ty)) {
503 std::vector<Init*> Elements;
505 // Verify that all of the elements of the list are subclasses of the
506 // appropriate class!
507 for (Init *I : getValues())
508 if (Init *CI = I->convertInitializerTo(LRT->getElementType()))
509 Elements.push_back(CI);
513 if (isa<ListRecTy>(getType()))
514 return ListInit::get(Elements, Ty);
521 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
522 std::vector<Init*> Vals;
523 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
524 if (Elements[i] >= size())
526 Vals.push_back(getElement(Elements[i]));
528 return ListInit::get(Vals, getType());
531 Record *ListInit::getElementAsRecord(unsigned i) const {
532 assert(i < Values.size() && "List element index out of range!");
533 DefInit *DI = dyn_cast<DefInit>(Values[i]);
535 PrintFatalError("Expected record in list!");
539 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
540 std::vector<Init*> Resolved;
541 Resolved.reserve(size());
542 bool Changed = false;
544 for (Init *CurElt : getValues()) {
549 CurElt = CurElt->resolveReferences(R, RV);
550 Changed |= E != CurElt;
551 } while (E != CurElt);
552 Resolved.push_back(E);
556 return ListInit::get(Resolved, getType());
557 return const_cast<ListInit *>(this);
560 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
561 unsigned Elt) const {
563 return nullptr; // Out of range reference.
564 Init *E = getElement(Elt);
565 // If the element is set to some value, or if we are resolving a reference
566 // to a specific variable and that variable is explicitly unset, then
567 // replace the VarListElementInit with it.
568 if (IRV || !isa<UnsetInit>(E))
573 std::string ListInit::getAsString() const {
574 std::string Result = "[";
575 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
576 if (i) Result += ", ";
577 Result += Values[i]->getAsString();
582 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
583 unsigned Elt) const {
584 Init *Resolved = resolveReferences(R, IRV);
585 OpInit *OResolved = dyn_cast<OpInit>(Resolved);
587 Resolved = OResolved->Fold(&R, nullptr);
590 if (Resolved != this) {
591 TypedInit *Typed = cast<TypedInit>(Resolved);
592 if (Init *New = Typed->resolveListElementReference(R, IRV, Elt))
594 return VarListElementInit::get(Typed, Elt);
600 Init *OpInit::getBit(unsigned Bit) const {
601 if (getType() == BitRecTy::get())
602 return const_cast<OpInit*>(this);
603 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
606 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
607 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
608 static DenseMap<Key, std::unique_ptr<UnOpInit>> ThePool;
610 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
612 std::unique_ptr<UnOpInit> &I = ThePool[TheKey];
613 if (!I) I.reset(new UnOpInit(opc, lhs, Type));
617 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
618 switch (getOpcode()) {
620 if (isa<StringRecTy>(getType())) {
621 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
624 if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
625 return StringInit::get(LHSd->getAsString());
627 if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
628 return StringInit::get(LHSi->getAsString());
630 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
631 std::string Name = LHSs->getValue();
633 // From TGParser::ParseIDValue
635 if (const RecordVal *RV = CurRec->getValue(Name)) {
636 if (RV->getType() != getType())
637 PrintFatalError("type mismatch in cast");
638 return VarInit::get(Name, RV->getType());
641 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
644 if (CurRec->isTemplateArg(TemplateArgName)) {
645 const RecordVal *RV = CurRec->getValue(TemplateArgName);
646 assert(RV && "Template arg doesn't exist??");
648 if (RV->getType() != getType())
649 PrintFatalError("type mismatch in cast");
651 return VarInit::get(TemplateArgName, RV->getType());
656 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
659 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
660 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
661 assert(RV && "Template arg doesn't exist??");
663 if (RV->getType() != getType())
664 PrintFatalError("type mismatch in cast");
666 return VarInit::get(MCName, RV->getType());
669 assert(CurRec && "NULL pointer");
670 if (Record *D = (CurRec->getRecords()).getDef(Name))
671 return DefInit::get(D);
673 PrintFatalError(CurRec->getLoc(),
674 "Undefined reference:'" + Name + "'\n");
680 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
681 assert(!LHSl->empty() && "Empty list in head");
682 return LHSl->getElement(0);
687 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
688 assert(!LHSl->empty() && "Empty list in tail");
689 // Note the +1. We can't just pass the result of getValues()
691 return ListInit::get(LHSl->getValues().slice(1), LHSl->getType());
696 if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
697 return IntInit::get(LHSl->empty());
698 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
699 return IntInit::get(LHSs->getValue().empty());
704 return const_cast<UnOpInit *>(this);
707 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
708 Init *lhs = LHS->resolveReferences(R, RV);
711 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, nullptr);
712 return Fold(&R, nullptr);
715 std::string UnOpInit::getAsString() const {
718 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
719 case HEAD: Result = "!head"; break;
720 case TAIL: Result = "!tail"; break;
721 case EMPTY: Result = "!empty"; break;
723 return Result + "(" + LHS->getAsString() + ")";
726 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
727 Init *rhs, RecTy *Type) {
729 std::pair<std::pair<unsigned, Init *>, Init *>,
733 static DenseMap<Key, std::unique_ptr<BinOpInit>> ThePool;
735 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
738 std::unique_ptr<BinOpInit> &I = ThePool[TheKey];
739 if (!I) I.reset(new BinOpInit(opc, lhs, rhs, Type));
743 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
744 switch (getOpcode()) {
746 DagInit *LHSs = dyn_cast<DagInit>(LHS);
747 DagInit *RHSs = dyn_cast<DagInit>(RHS);
749 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
750 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
751 if (!LOp || !ROp || LOp->getDef() != ROp->getDef())
752 PrintFatalError("Concated Dag operators do not match!");
753 std::vector<Init*> Args;
754 std::vector<std::string> ArgNames;
755 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
756 Args.push_back(LHSs->getArg(i));
757 ArgNames.push_back(LHSs->getArgName(i));
759 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
760 Args.push_back(RHSs->getArg(i));
761 ArgNames.push_back(RHSs->getArgName(i));
763 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
768 ListInit *LHSs = dyn_cast<ListInit>(LHS);
769 ListInit *RHSs = dyn_cast<ListInit>(RHS);
771 std::vector<Init *> Args;
772 Args.insert(Args.end(), LHSs->begin(), LHSs->end());
773 Args.insert(Args.end(), RHSs->begin(), RHSs->end());
774 return ListInit::get(
775 Args, cast<ListRecTy>(LHSs->getType())->getElementType());
780 StringInit *LHSs = dyn_cast<StringInit>(LHS);
781 StringInit *RHSs = dyn_cast<StringInit>(RHS);
783 return StringInit::get(LHSs->getValue() + RHSs->getValue());
787 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
788 // to string objects.
790 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
792 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
795 return IntInit::get(L->getValue() == R->getValue());
797 StringInit *LHSs = dyn_cast<StringInit>(LHS);
798 StringInit *RHSs = dyn_cast<StringInit>(RHS);
800 // Make sure we've resolved
802 return IntInit::get(LHSs->getValue() == RHSs->getValue());
812 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
814 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
816 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
818 switch (getOpcode()) {
819 default: llvm_unreachable("Bad opcode!");
820 case ADD: Result = LHSv + RHSv; break;
821 case AND: Result = LHSv & RHSv; break;
822 case SHL: Result = LHSv << RHSv; break;
823 case SRA: Result = LHSv >> RHSv; break;
824 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
826 return IntInit::get(Result);
831 return const_cast<BinOpInit *>(this);
834 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
835 Init *lhs = LHS->resolveReferences(R, RV);
836 Init *rhs = RHS->resolveReferences(R, RV);
838 if (LHS != lhs || RHS != rhs)
839 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R,nullptr);
840 return Fold(&R, nullptr);
843 std::string BinOpInit::getAsString() const {
846 case CONCAT: Result = "!con"; break;
847 case ADD: Result = "!add"; break;
848 case AND: Result = "!and"; break;
849 case SHL: Result = "!shl"; break;
850 case SRA: Result = "!sra"; break;
851 case SRL: Result = "!srl"; break;
852 case EQ: Result = "!eq"; break;
853 case LISTCONCAT: Result = "!listconcat"; break;
854 case STRCONCAT: Result = "!strconcat"; break;
856 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
859 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs,
863 std::pair<std::pair<unsigned, RecTy *>, Init *>,
869 static DenseMap<Key, std::unique_ptr<TernOpInit>> ThePool;
871 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
877 std::unique_ptr<TernOpInit> &I = ThePool[TheKey];
878 if (!I) I.reset(new TernOpInit(opc, lhs, mhs, rhs, Type));
882 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
883 Record *CurRec, MultiClass *CurMultiClass);
885 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
886 RecTy *Type, Record *CurRec,
887 MultiClass *CurMultiClass) {
888 // If this is a dag, recurse
889 if (auto *TArg = dyn_cast<TypedInit>(Arg))
890 if (isa<DagRecTy>(TArg->getType()))
891 return ForeachHelper(LHS, Arg, RHSo, Type, CurRec, CurMultiClass);
893 std::vector<Init *> NewOperands;
894 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
895 if (auto *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i))) {
896 if (Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
897 Type, CurRec, CurMultiClass))
898 NewOperands.push_back(Result);
900 NewOperands.push_back(Arg);
901 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
902 NewOperands.push_back(Arg);
904 NewOperands.push_back(RHSo->getOperand(i));
908 // Now run the operator and use its result as the new leaf
909 const OpInit *NewOp = RHSo->clone(NewOperands);
910 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
911 return (NewVal != NewOp) ? NewVal : nullptr;
914 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
915 Record *CurRec, MultiClass *CurMultiClass) {
916 DagInit *MHSd = dyn_cast<DagInit>(MHS);
917 ListInit *MHSl = dyn_cast<ListInit>(MHS);
919 OpInit *RHSo = dyn_cast<OpInit>(RHS);
922 PrintFatalError(CurRec->getLoc(), "!foreach requires an operator\n");
924 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
927 PrintFatalError(CurRec->getLoc(), "!foreach requires typed variable\n");
929 if ((MHSd && isa<DagRecTy>(Type)) || (MHSl && isa<ListRecTy>(Type))) {
931 Init *Val = MHSd->getOperator();
932 Init *Result = EvaluateOperation(RHSo, LHS, Val,
933 Type, CurRec, CurMultiClass);
937 std::vector<std::pair<Init *, std::string> > args;
938 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
939 Init *Arg = MHSd->getArg(i);
940 std::string ArgName = MHSd->getArgName(i);
943 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
944 CurRec, CurMultiClass);
948 // TODO: Process arg names
949 args.push_back(std::make_pair(Arg, ArgName));
952 return DagInit::get(Val, "", args);
955 std::vector<Init *> NewOperands;
956 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
958 for (Init *&Item : NewList) {
960 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
961 // First, replace the foreach variable with the list item
962 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString())
963 NewOperands.push_back(Item);
965 NewOperands.push_back(RHSo->getOperand(i));
968 // Now run the operator and use its result as the new list item
969 const OpInit *NewOp = RHSo->clone(NewOperands);
970 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
971 if (NewItem != NewOp)
974 return ListInit::get(NewList, MHSl->getType());
980 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
981 switch (getOpcode()) {
983 DefInit *LHSd = dyn_cast<DefInit>(LHS);
984 VarInit *LHSv = dyn_cast<VarInit>(LHS);
985 StringInit *LHSs = dyn_cast<StringInit>(LHS);
987 DefInit *MHSd = dyn_cast<DefInit>(MHS);
988 VarInit *MHSv = dyn_cast<VarInit>(MHS);
989 StringInit *MHSs = dyn_cast<StringInit>(MHS);
991 DefInit *RHSd = dyn_cast<DefInit>(RHS);
992 VarInit *RHSv = dyn_cast<VarInit>(RHS);
993 StringInit *RHSs = dyn_cast<StringInit>(RHS);
995 if (LHSd && MHSd && RHSd) {
996 Record *Val = RHSd->getDef();
997 if (LHSd->getAsString() == RHSd->getAsString())
998 Val = MHSd->getDef();
999 return DefInit::get(Val);
1001 if (LHSv && MHSv && RHSv) {
1002 std::string Val = RHSv->getName();
1003 if (LHSv->getAsString() == RHSv->getAsString())
1004 Val = MHSv->getName();
1005 return VarInit::get(Val, getType());
1007 if (LHSs && MHSs && RHSs) {
1008 std::string Val = RHSs->getValue();
1010 std::string::size_type found;
1011 std::string::size_type idx = 0;
1013 found = Val.find(LHSs->getValue(), idx);
1014 if (found == std::string::npos)
1016 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1017 idx = found + MHSs->getValue().size();
1020 return StringInit::get(Val);
1026 if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1027 CurRec, CurMultiClass))
1033 IntInit *LHSi = dyn_cast<IntInit>(LHS);
1034 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1035 LHSi = dyn_cast<IntInit>(I);
1037 if (LHSi->getValue())
1045 return const_cast<TernOpInit *>(this);
1048 Init *TernOpInit::resolveReferences(Record &R,
1049 const RecordVal *RV) const {
1050 Init *lhs = LHS->resolveReferences(R, RV);
1052 if (Opc == IF && lhs != LHS) {
1053 IntInit *Value = dyn_cast<IntInit>(lhs);
1054 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1055 Value = dyn_cast<IntInit>(I);
1058 if (Value->getValue()) {
1059 Init *mhs = MHS->resolveReferences(R, RV);
1060 return (TernOpInit::get(getOpcode(), lhs, mhs,
1061 RHS, getType()))->Fold(&R, nullptr);
1063 Init *rhs = RHS->resolveReferences(R, RV);
1064 return (TernOpInit::get(getOpcode(), lhs, MHS,
1065 rhs, getType()))->Fold(&R, nullptr);
1069 Init *mhs = MHS->resolveReferences(R, RV);
1070 Init *rhs = RHS->resolveReferences(R, RV);
1072 if (LHS != lhs || MHS != mhs || RHS != rhs)
1073 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1074 getType()))->Fold(&R, nullptr);
1075 return Fold(&R, nullptr);
1078 std::string TernOpInit::getAsString() const {
1081 case SUBST: Result = "!subst"; break;
1082 case FOREACH: Result = "!foreach"; break;
1083 case IF: Result = "!if"; break;
1085 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", " +
1086 RHS->getAsString() + ")";
1089 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1090 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
1091 if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
1092 return Field->getType();
1097 TypedInit::convertInitializerTo(RecTy *Ty) const {
1098 if (isa<IntRecTy>(Ty)) {
1099 if (getType()->typeIsConvertibleTo(Ty))
1100 return const_cast<TypedInit *>(this);
1104 if (isa<StringRecTy>(Ty)) {
1105 if (isa<StringRecTy>(getType()))
1106 return const_cast<TypedInit *>(this);
1110 if (isa<BitRecTy>(Ty)) {
1111 // Accept variable if it is already of bit type!
1112 if (isa<BitRecTy>(getType()))
1113 return const_cast<TypedInit *>(this);
1114 if (auto *BitsTy = dyn_cast<BitsRecTy>(getType())) {
1115 // Accept only bits<1> expression.
1116 if (BitsTy->getNumBits() == 1)
1117 return const_cast<TypedInit *>(this);
1120 // Ternary !if can be converted to bit, but only if both sides are
1121 // convertible to a bit.
1122 if (const auto *TOI = dyn_cast<TernOpInit>(this)) {
1123 if (TOI->getOpcode() == TernOpInit::TernaryOp::IF &&
1124 TOI->getMHS()->convertInitializerTo(BitRecTy::get()) &&
1125 TOI->getRHS()->convertInitializerTo(BitRecTy::get()))
1126 return const_cast<TypedInit *>(this);
1132 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
1133 if (BRT->getNumBits() == 1 && isa<BitRecTy>(getType()))
1134 return BitsInit::get(const_cast<TypedInit *>(this));
1136 if (getType()->typeIsConvertibleTo(BRT)) {
1137 SmallVector<Init *, 16> NewBits(BRT->getNumBits());
1139 for (unsigned i = 0; i != BRT->getNumBits(); ++i)
1140 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), i);
1141 return BitsInit::get(NewBits);
1147 if (auto *DLRT = dyn_cast<ListRecTy>(Ty)) {
1148 if (auto *SLRT = dyn_cast<ListRecTy>(getType()))
1149 if (SLRT->getElementType()->typeIsConvertibleTo(DLRT->getElementType()))
1150 return const_cast<TypedInit *>(this);
1154 if (auto *DRT = dyn_cast<DagRecTy>(Ty)) {
1155 if (getType()->typeIsConvertibleTo(DRT))
1156 return const_cast<TypedInit *>(this);
1160 if (auto *SRRT = dyn_cast<RecordRecTy>(Ty)) {
1161 // Ensure that this is compatible with Rec.
1162 if (RecordRecTy *DRRT = dyn_cast<RecordRecTy>(getType()))
1163 if (DRRT->getRecord()->isSubClassOf(SRRT->getRecord()) ||
1164 DRRT->getRecord() == SRRT->getRecord())
1165 return const_cast<TypedInit *>(this);
1173 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1174 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1175 if (!T) return nullptr; // Cannot subscript a non-bits variable.
1176 unsigned NumBits = T->getNumBits();
1178 SmallVector<Init *, 16> NewBits(Bits.size());
1179 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1180 if (Bits[i] >= NumBits)
1183 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1185 return BitsInit::get(NewBits);
1189 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1190 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1191 if (!T) return nullptr; // Cannot subscript a non-list variable.
1193 if (Elements.size() == 1)
1194 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1196 std::vector<Init*> ListInits;
1197 ListInits.reserve(Elements.size());
1198 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1199 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1201 return ListInit::get(ListInits, T);
1205 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1206 Init *Value = StringInit::get(VN);
1207 return VarInit::get(Value, T);
1210 VarInit *VarInit::get(Init *VN, RecTy *T) {
1211 typedef std::pair<RecTy *, Init *> Key;
1212 static DenseMap<Key, std::unique_ptr<VarInit>> ThePool;
1214 Key TheKey(std::make_pair(T, VN));
1216 std::unique_ptr<VarInit> &I = ThePool[TheKey];
1217 if (!I) I.reset(new VarInit(VN, T));
1221 const std::string &VarInit::getName() const {
1222 StringInit *NameString = cast<StringInit>(getNameInit());
1223 return NameString->getValue();
1226 Init *VarInit::getBit(unsigned Bit) const {
1227 if (getType() == BitRecTy::get())
1228 return const_cast<VarInit*>(this);
1229 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1232 Init *VarInit::resolveListElementReference(Record &R,
1233 const RecordVal *IRV,
1234 unsigned Elt) const {
1235 if (R.isTemplateArg(getNameInit())) return nullptr;
1236 if (IRV && IRV->getNameInit() != getNameInit()) return nullptr;
1238 RecordVal *RV = R.getValue(getNameInit());
1239 assert(RV && "Reference to a non-existent variable?");
1240 ListInit *LI = dyn_cast<ListInit>(RV->getValue());
1242 return VarListElementInit::get(cast<TypedInit>(RV->getValue()), Elt);
1244 if (Elt >= LI->size())
1245 return nullptr; // Out of range reference.
1246 Init *E = LI->getElement(Elt);
1247 // If the element is set to some value, or if we are resolving a reference
1248 // to a specific variable and that variable is explicitly unset, then
1249 // replace the VarListElementInit with it.
1250 if (IRV || !isa<UnsetInit>(E))
1256 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1257 if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
1258 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1259 return RV->getType();
1263 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1264 const std::string &FieldName) const {
1265 if (isa<RecordRecTy>(getType()))
1266 if (const RecordVal *Val = R.getValue(VarName)) {
1267 if (RV != Val && (RV || isa<UnsetInit>(Val->getValue())))
1269 Init *TheInit = Val->getValue();
1270 assert(TheInit != this && "Infinite loop detected!");
1271 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1278 /// resolveReferences - This method is used by classes that refer to other
1279 /// variables which may not be defined at the time the expression is formed.
1280 /// If a value is set for the variable later, this method will be called on
1281 /// users of the value to allow the value to propagate out.
1283 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1284 if (RecordVal *Val = R.getValue(VarName))
1285 if (RV == Val || (!RV && !isa<UnsetInit>(Val->getValue())))
1286 return Val->getValue();
1287 return const_cast<VarInit *>(this);
1290 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1291 typedef std::pair<TypedInit *, unsigned> Key;
1292 static DenseMap<Key, std::unique_ptr<VarBitInit>> ThePool;
1294 Key TheKey(std::make_pair(T, B));
1296 std::unique_ptr<VarBitInit> &I = ThePool[TheKey];
1297 if (!I) I.reset(new VarBitInit(T, B));
1301 Init *VarBitInit::convertInitializerTo(RecTy *Ty) const {
1302 if (isa<BitRecTy>(Ty))
1303 return const_cast<VarBitInit *>(this);
1308 std::string VarBitInit::getAsString() const {
1309 return TI->getAsString() + "{" + utostr(Bit) + "}";
1312 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1313 Init *I = TI->resolveReferences(R, RV);
1315 return I->getBit(getBitNum());
1317 return const_cast<VarBitInit*>(this);
1320 VarListElementInit *VarListElementInit::get(TypedInit *T,
1322 typedef std::pair<TypedInit *, unsigned> Key;
1323 static DenseMap<Key, std::unique_ptr<VarListElementInit>> ThePool;
1325 Key TheKey(std::make_pair(T, E));
1327 std::unique_ptr<VarListElementInit> &I = ThePool[TheKey];
1328 if (!I) I.reset(new VarListElementInit(T, E));
1332 std::string VarListElementInit::getAsString() const {
1333 return TI->getAsString() + "[" + utostr(Element) + "]";
1337 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1338 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1341 return const_cast<VarListElementInit *>(this);
1344 Init *VarListElementInit::getBit(unsigned Bit) const {
1345 if (getType() == BitRecTy::get())
1346 return const_cast<VarListElementInit*>(this);
1347 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1350 Init *VarListElementInit:: resolveListElementReference(Record &R,
1351 const RecordVal *RV,
1352 unsigned Elt) const {
1353 if (Init *Result = TI->resolveListElementReference(R, RV, Element)) {
1354 if (TypedInit *TInit = dyn_cast<TypedInit>(Result)) {
1355 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1356 if (Result2) return Result2;
1357 return VarListElementInit::get(TInit, Elt);
1365 DefInit *DefInit::get(Record *R) {
1366 return R->getDefInit();
1369 Init *DefInit::convertInitializerTo(RecTy *Ty) const {
1370 if (auto *RRT = dyn_cast<RecordRecTy>(Ty))
1371 if (getDef()->isSubClassOf(RRT->getRecord()))
1372 return const_cast<DefInit *>(this);
1376 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1377 if (const RecordVal *RV = Def->getValue(FieldName))
1378 return RV->getType();
1382 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1383 const std::string &FieldName) const {
1384 return Def->getValue(FieldName)->getValue();
1388 std::string DefInit::getAsString() const {
1389 return Def->getName();
1392 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1393 typedef std::pair<Init *, TableGenStringKey> Key;
1394 static DenseMap<Key, std::unique_ptr<FieldInit>> ThePool;
1396 Key TheKey(std::make_pair(R, FN));
1398 std::unique_ptr<FieldInit> &I = ThePool[TheKey];
1399 if (!I) I.reset(new FieldInit(R, FN));
1403 Init *FieldInit::getBit(unsigned Bit) const {
1404 if (getType() == BitRecTy::get())
1405 return const_cast<FieldInit*>(this);
1406 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1409 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1410 unsigned Elt) const {
1411 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1412 if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
1413 if (Elt >= LI->size()) return nullptr;
1414 Init *E = LI->getElement(Elt);
1416 // If the element is set to some value, or if we are resolving a
1417 // reference to a specific variable and that variable is explicitly
1418 // unset, then replace the VarListElementInit with it.
1419 if (RV || !isa<UnsetInit>(E))
1425 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1426 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1428 if (Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName)) {
1429 Init *BVR = BitsVal->resolveReferences(R, RV);
1430 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1434 return FieldInit::get(NewRec, FieldName);
1435 return const_cast<FieldInit *>(this);
1438 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, const std::string &VN,
1439 ArrayRef<Init *> ArgRange,
1440 ArrayRef<std::string> NameRange) {
1444 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1445 ArrayRef<std::string>::iterator Name = NameRange.begin();
1446 while (Arg != ArgRange.end()) {
1447 assert(Name != NameRange.end() && "Arg name underflow!");
1448 ID.AddPointer(*Arg++);
1449 ID.AddString(*Name++);
1451 assert(Name == NameRange.end() && "Arg name overflow!");
1455 DagInit::get(Init *V, const std::string &VN,
1456 ArrayRef<Init *> ArgRange,
1457 ArrayRef<std::string> NameRange) {
1458 static FoldingSet<DagInit> ThePool;
1459 static std::vector<std::unique_ptr<DagInit>> TheActualPool;
1461 FoldingSetNodeID ID;
1462 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1465 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1468 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1469 ThePool.InsertNode(I, IP);
1470 TheActualPool.push_back(std::unique_ptr<DagInit>(I));
1475 DagInit::get(Init *V, const std::string &VN,
1476 const std::vector<std::pair<Init*, std::string> > &args) {
1477 std::vector<Init *> Args;
1478 std::vector<std::string> Names;
1480 for (const auto &Arg : args) {
1481 Args.push_back(Arg.first);
1482 Names.push_back(Arg.second);
1485 return DagInit::get(V, VN, Args, Names);
1488 void DagInit::Profile(FoldingSetNodeID &ID) const {
1489 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1492 Init *DagInit::convertInitializerTo(RecTy *Ty) const {
1493 if (isa<DagRecTy>(Ty))
1494 return const_cast<DagInit *>(this);
1499 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1500 std::vector<Init*> NewArgs;
1501 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1502 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1504 Init *Op = Val->resolveReferences(R, RV);
1506 if (Args != NewArgs || Op != Val)
1507 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1509 return const_cast<DagInit *>(this);
1513 std::string DagInit::getAsString() const {
1514 std::string Result = "(" + Val->getAsString();
1515 if (!ValName.empty())
1516 Result += ":" + ValName;
1517 if (!Args.empty()) {
1518 Result += " " + Args[0]->getAsString();
1519 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1520 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1521 Result += ", " + Args[i]->getAsString();
1522 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1525 return Result + ")";
1529 //===----------------------------------------------------------------------===//
1530 // Other implementations
1531 //===----------------------------------------------------------------------===//
1533 RecordVal::RecordVal(Init *N, RecTy *T, bool P)
1534 : NameAndPrefix(N, P), Ty(T) {
1535 Value = UnsetInit::get()->convertInitializerTo(Ty);
1536 assert(Value && "Cannot create unset value for current type!");
1539 RecordVal::RecordVal(const std::string &N, RecTy *T, bool P)
1540 : NameAndPrefix(StringInit::get(N), P), Ty(T) {
1541 Value = UnsetInit::get()->convertInitializerTo(Ty);
1542 assert(Value && "Cannot create unset value for current type!");
1545 const std::string &RecordVal::getName() const {
1546 return cast<StringInit>(getNameInit())->getValue();
1549 void RecordVal::dump() const { errs() << *this; }
1551 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1552 if (getPrefix()) OS << "field ";
1553 OS << *getType() << " " << getNameInitAsString();
1556 OS << " = " << *getValue();
1558 if (PrintSem) OS << ";\n";
1561 unsigned Record::LastID = 0;
1563 void Record::init() {
1566 // Every record potentially has a def at the top. This value is
1567 // replaced with the top-level def name at instantiation time.
1568 RecordVal DN("NAME", StringRecTy::get(), 0);
1572 void Record::checkName() {
1573 // Ensure the record name has string type.
1574 const TypedInit *TypedName = cast<const TypedInit>(Name);
1575 RecTy *Type = TypedName->getType();
1576 if (!isa<StringRecTy>(Type))
1577 PrintFatalError(getLoc(), "Record name is not a string!");
1580 DefInit *Record::getDefInit() {
1581 static DenseMap<Record *, std::unique_ptr<DefInit>> ThePool;
1585 std::unique_ptr<DefInit> &I = ThePool[this];
1586 if (!I) I.reset(new DefInit(this, new RecordRecTy(this)));
1590 const std::string &Record::getName() const {
1591 return cast<StringInit>(Name)->getValue();
1594 void Record::setName(Init *NewName) {
1597 // DO NOT resolve record values to the name at this point because
1598 // there might be default values for arguments of this def. Those
1599 // arguments might not have been resolved yet so we don't want to
1600 // prematurely assume values for those arguments were not passed to
1603 // Nonetheless, it may be that some of this Record's values
1604 // reference the record name. Indeed, the reason for having the
1605 // record name be an Init is to provide this flexibility. The extra
1606 // resolve steps after completely instantiating defs takes care of
1607 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1610 void Record::setName(const std::string &Name) {
1611 setName(StringInit::get(Name));
1614 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1615 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1617 void Record::resolveReferencesTo(const RecordVal *RV) {
1618 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1619 if (RV == &Values[i]) // Skip resolve the same field as the given one
1621 if (Init *V = Values[i].getValue())
1622 if (Values[i].setValue(V->resolveReferences(*this, RV)))
1623 PrintFatalError(getLoc(), "Invalid value is found when setting '" +
1624 Values[i].getNameInitAsString() +
1625 "' after resolving references" +
1626 (RV ? " against '" + RV->getNameInitAsString() +
1627 "' of (" + RV->getValue()->getAsUnquotedString() +
1631 Init *OldName = getNameInit();
1632 Init *NewName = Name->resolveReferences(*this, RV);
1633 if (NewName != OldName) {
1634 // Re-register with RecordKeeper.
1639 void Record::dump() const { errs() << *this; }
1641 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1642 OS << R.getNameInitAsString();
1644 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1645 if (!TArgs.empty()) {
1647 bool NeedComma = false;
1648 for (const Init *TA : TArgs) {
1649 if (NeedComma) OS << ", ";
1651 const RecordVal *RV = R.getValue(TA);
1652 assert(RV && "Template argument record not found??");
1653 RV->print(OS, false);
1659 const std::vector<Record*> &SC = R.getSuperClasses();
1662 for (const Record *Super : SC)
1663 OS << " " << Super->getNameInitAsString();
1667 for (const RecordVal &Val : R.getValues())
1668 if (Val.getPrefix() && !R.isTemplateArg(Val.getName()))
1670 for (const RecordVal &Val : R.getValues())
1671 if (!Val.getPrefix() && !R.isTemplateArg(Val.getName()))
1677 /// getValueInit - Return the initializer for a value with the specified name,
1678 /// or abort if the field does not exist.
1680 Init *Record::getValueInit(StringRef FieldName) const {
1681 const RecordVal *R = getValue(FieldName);
1682 if (!R || !R->getValue())
1683 PrintFatalError(getLoc(), "Record `" + getName() +
1684 "' does not have a field named `" + FieldName + "'!\n");
1685 return R->getValue();
1689 /// getValueAsString - This method looks up the specified field and returns its
1690 /// value as a string, aborts if the field does not exist or if
1691 /// the value is not a string.
1693 std::string Record::getValueAsString(StringRef FieldName) const {
1694 const RecordVal *R = getValue(FieldName);
1695 if (!R || !R->getValue())
1696 PrintFatalError(getLoc(), "Record `" + getName() +
1697 "' does not have a field named `" + FieldName + "'!\n");
1699 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1700 return SI->getValue();
1701 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1702 FieldName + "' does not have a string initializer!");
1705 /// getValueAsBitsInit - This method looks up the specified field and returns
1706 /// its value as a BitsInit, aborts if the field does not exist or if
1707 /// the value is not the right type.
1709 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1710 const RecordVal *R = getValue(FieldName);
1711 if (!R || !R->getValue())
1712 PrintFatalError(getLoc(), "Record `" + getName() +
1713 "' does not have a field named `" + FieldName + "'!\n");
1715 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
1717 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1718 FieldName + "' does not have a BitsInit initializer!");
1721 /// getValueAsListInit - This method looks up the specified field and returns
1722 /// its value as a ListInit, aborting if the field does not exist or if
1723 /// the value is not the right type.
1725 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1726 const RecordVal *R = getValue(FieldName);
1727 if (!R || !R->getValue())
1728 PrintFatalError(getLoc(), "Record `" + getName() +
1729 "' does not have a field named `" + FieldName + "'!\n");
1731 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
1733 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1734 FieldName + "' does not have a list initializer!");
1737 /// getValueAsListOfDefs - This method looks up the specified field and returns
1738 /// its value as a vector of records, aborting if the field does not exist
1739 /// or if the value is not the right type.
1741 std::vector<Record*>
1742 Record::getValueAsListOfDefs(StringRef FieldName) const {
1743 ListInit *List = getValueAsListInit(FieldName);
1744 std::vector<Record*> Defs;
1745 for (Init *I : List->getValues()) {
1746 if (DefInit *DI = dyn_cast<DefInit>(I))
1747 Defs.push_back(DI->getDef());
1749 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1750 FieldName + "' list is not entirely DefInit!");
1755 /// getValueAsInt - This method looks up the specified field and returns its
1756 /// value as an int64_t, aborting if the field does not exist or if the value
1757 /// is not the right type.
1759 int64_t Record::getValueAsInt(StringRef FieldName) const {
1760 const RecordVal *R = getValue(FieldName);
1761 if (!R || !R->getValue())
1762 PrintFatalError(getLoc(), "Record `" + getName() +
1763 "' does not have a field named `" + FieldName + "'!\n");
1765 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
1766 return II->getValue();
1767 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1768 FieldName + "' does not have an int initializer!");
1771 /// getValueAsListOfInts - This method looks up the specified field and returns
1772 /// its value as a vector of integers, aborting if the field does not exist or
1773 /// if the value is not the right type.
1775 std::vector<int64_t>
1776 Record::getValueAsListOfInts(StringRef FieldName) const {
1777 ListInit *List = getValueAsListInit(FieldName);
1778 std::vector<int64_t> Ints;
1779 for (Init *I : List->getValues()) {
1780 if (IntInit *II = dyn_cast<IntInit>(I))
1781 Ints.push_back(II->getValue());
1783 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1784 FieldName + "' does not have a list of ints initializer!");
1789 /// getValueAsListOfStrings - This method looks up the specified field and
1790 /// returns its value as a vector of strings, aborting if the field does not
1791 /// exist or if the value is not the right type.
1793 std::vector<std::string>
1794 Record::getValueAsListOfStrings(StringRef FieldName) const {
1795 ListInit *List = getValueAsListInit(FieldName);
1796 std::vector<std::string> Strings;
1797 for (Init *I : List->getValues()) {
1798 if (StringInit *SI = dyn_cast<StringInit>(I))
1799 Strings.push_back(SI->getValue());
1801 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1802 FieldName + "' does not have a list of strings initializer!");
1807 /// getValueAsDef - This method looks up the specified field and returns its
1808 /// value as a Record, aborting if the field does not exist or if the value
1809 /// is not the right type.
1811 Record *Record::getValueAsDef(StringRef FieldName) const {
1812 const RecordVal *R = getValue(FieldName);
1813 if (!R || !R->getValue())
1814 PrintFatalError(getLoc(), "Record `" + getName() +
1815 "' does not have a field named `" + FieldName + "'!\n");
1817 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
1818 return DI->getDef();
1819 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1820 FieldName + "' does not have a def initializer!");
1823 /// getValueAsBit - This method looks up the specified field and returns its
1824 /// value as a bit, aborting if the field does not exist or if the value is
1825 /// not the right type.
1827 bool Record::getValueAsBit(StringRef FieldName) const {
1828 const RecordVal *R = getValue(FieldName);
1829 if (!R || !R->getValue())
1830 PrintFatalError(getLoc(), "Record `" + getName() +
1831 "' does not have a field named `" + FieldName + "'!\n");
1833 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1834 return BI->getValue();
1835 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1836 FieldName + "' does not have a bit initializer!");
1839 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1840 const RecordVal *R = getValue(FieldName);
1841 if (!R || !R->getValue())
1842 PrintFatalError(getLoc(), "Record `" + getName() +
1843 "' does not have a field named `" + FieldName.str() + "'!\n");
1845 if (isa<UnsetInit>(R->getValue())) {
1850 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1851 return BI->getValue();
1852 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1853 FieldName + "' does not have a bit initializer!");
1856 /// getValueAsDag - This method looks up the specified field and returns its
1857 /// value as an Dag, aborting if the field does not exist or if the value is
1858 /// not the right type.
1860 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1861 const RecordVal *R = getValue(FieldName);
1862 if (!R || !R->getValue())
1863 PrintFatalError(getLoc(), "Record `" + getName() +
1864 "' does not have a field named `" + FieldName + "'!\n");
1866 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
1868 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1869 FieldName + "' does not have a dag initializer!");
1873 void MultiClass::dump() const {
1874 errs() << "Record:\n";
1877 errs() << "Defs:\n";
1878 for (const auto &Proto : DefPrototypes)
1883 void RecordKeeper::dump() const { errs() << *this; }
1885 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1886 OS << "------------- Classes -----------------\n";
1887 for (const auto &C : RK.getClasses())
1888 OS << "class " << *C.second;
1890 OS << "------------- Defs -----------------\n";
1891 for (const auto &D : RK.getDefs())
1892 OS << "def " << *D.second;
1897 /// getAllDerivedDefinitions - This method returns all concrete definitions
1898 /// that derive from the specified class name. If a class with the specified
1899 /// name does not exist, an error is printed and true is returned.
1900 std::vector<Record*>
1901 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
1902 Record *Class = getClass(ClassName);
1904 PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
1906 std::vector<Record*> Defs;
1907 for (const auto &D : getDefs())
1908 if (D.second->isSubClassOf(Class))
1909 Defs.push_back(D.second.get());
1914 /// QualifyName - Return an Init with a qualifier prefix referring
1915 /// to CurRec's name.
1916 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1917 Init *Name, const std::string &Scoper) {
1918 RecTy *Type = cast<TypedInit>(Name)->getType();
1920 BinOpInit *NewName =
1921 BinOpInit::get(BinOpInit::STRCONCAT,
1922 BinOpInit::get(BinOpInit::STRCONCAT,
1923 CurRec.getNameInit(),
1924 StringInit::get(Scoper),
1925 Type)->Fold(&CurRec, CurMultiClass),
1929 if (CurMultiClass && Scoper != "::") {
1931 BinOpInit::get(BinOpInit::STRCONCAT,
1932 BinOpInit::get(BinOpInit::STRCONCAT,
1933 CurMultiClass->Rec.getNameInit(),
1934 StringInit::get("::"),
1935 Type)->Fold(&CurRec, CurMultiClass),
1936 NewName->Fold(&CurRec, CurMultiClass),
1940 return NewName->Fold(&CurRec, CurMultiClass);
1943 /// QualifyName - Return an Init with a qualifier prefix referring
1944 /// to CurRec's name.
1945 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1946 const std::string &Name,
1947 const std::string &Scoper) {
1948 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);