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 /// This is a wrapper for std::string suitable for using as a key to a DenseMap.
36 /// 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 CodeRecTy CodeRecTy::Shared;
86 IntRecTy IntRecTy::Shared;
87 StringRecTy StringRecTy::Shared;
88 DagRecTy DagRecTy::Shared;
90 LLVM_DUMP_METHOD void RecTy::dump() const { print(errs()); }
92 ListRecTy *RecTy::getListTy() {
94 ListTy.reset(new ListRecTy(this));
98 bool RecTy::typeIsConvertibleTo(const RecTy *RHS) const {
99 assert(RHS && "NULL pointer");
100 return Kind == RHS->getRecTyKind();
103 bool BitRecTy::typeIsConvertibleTo(const RecTy *RHS) const{
104 if (RecTy::typeIsConvertibleTo(RHS) || RHS->getRecTyKind() == IntRecTyKind)
106 if (const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
107 return BitsTy->getNumBits() == 1;
111 BitsRecTy *BitsRecTy::get(unsigned Sz) {
112 static std::vector<std::unique_ptr<BitsRecTy>> Shared;
113 if (Sz >= Shared.size())
114 Shared.resize(Sz + 1);
115 std::unique_ptr<BitsRecTy> &Ty = Shared[Sz];
117 Ty.reset(new BitsRecTy(Sz));
121 std::string BitsRecTy::getAsString() const {
122 return "bits<" + utostr(Size) + ">";
125 bool BitsRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
126 if (RecTy::typeIsConvertibleTo(RHS)) //argument and the sender are same type
127 return cast<BitsRecTy>(RHS)->Size == Size;
128 RecTyKind kind = RHS->getRecTyKind();
129 return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
132 bool IntRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
133 RecTyKind kind = RHS->getRecTyKind();
134 return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
137 std::string StringRecTy::getAsString() const {
141 std::string ListRecTy::getAsString() const {
142 return "list<" + Ty->getAsString() + ">";
145 bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
146 if (const auto *ListTy = dyn_cast<ListRecTy>(RHS))
147 return Ty->typeIsConvertibleTo(ListTy->getElementType());
151 std::string DagRecTy::getAsString() const {
155 RecordRecTy *RecordRecTy::get(Record *R) {
156 return dyn_cast<RecordRecTy>(R->getDefInit()->getType());
159 std::string RecordRecTy::getAsString() const {
160 return Rec->getName();
163 bool RecordRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
164 const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
168 if (RTy->getRecord() == Rec || Rec->isSubClassOf(RTy->getRecord()))
171 for (const auto &SCPair : RTy->getRecord()->getSuperClasses())
172 if (Rec->isSubClassOf(SCPair.first))
178 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
179 if (T1->typeIsConvertibleTo(T2))
181 if (T2->typeIsConvertibleTo(T1))
184 // If one is a Record type, check superclasses
185 if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
186 // See if T2 inherits from a type T1 also inherits from
187 for (const auto &SuperPair1 : RecTy1->getRecord()->getSuperClasses()) {
188 RecordRecTy *SuperRecTy1 = RecordRecTy::get(SuperPair1.first);
189 RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
194 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) {
195 // See if T1 inherits from a type T2 also inherits from
196 for (const auto &SuperPair2 : RecTy2->getRecord()->getSuperClasses()) {
197 RecordRecTy *SuperRecTy2 = RecordRecTy::get(SuperPair2.first);
198 RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
207 //===----------------------------------------------------------------------===//
208 // Initializer implementations
209 //===----------------------------------------------------------------------===//
211 void Init::anchor() { }
212 LLVM_DUMP_METHOD void Init::dump() const { return print(errs()); }
214 UnsetInit *UnsetInit::get() {
215 static UnsetInit TheInit;
219 Init *UnsetInit::convertInitializerTo(RecTy *Ty) const {
220 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
221 SmallVector<Init *, 16> NewBits(BRT->getNumBits());
223 for (unsigned i = 0; i != BRT->getNumBits(); ++i)
224 NewBits[i] = UnsetInit::get();
226 return BitsInit::get(NewBits);
229 // All other types can just be returned.
230 return const_cast<UnsetInit *>(this);
233 BitInit *BitInit::get(bool V) {
234 static BitInit True(true);
235 static BitInit False(false);
237 return V ? &True : &False;
240 Init *BitInit::convertInitializerTo(RecTy *Ty) const {
241 if (isa<BitRecTy>(Ty))
242 return const_cast<BitInit *>(this);
244 if (isa<IntRecTy>(Ty))
245 return IntInit::get(getValue());
247 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
248 // Can only convert single bit.
249 if (BRT->getNumBits() == 1)
250 return BitsInit::get(const_cast<BitInit *>(this));
257 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
258 ID.AddInteger(Range.size());
260 for (Init *I : Range)
264 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
265 static FoldingSet<BitsInit> ThePool;
266 static std::vector<std::unique_ptr<BitsInit>> TheActualPool;
269 ProfileBitsInit(ID, Range);
272 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
275 void *Mem = ::operator new (totalSizeToAlloc<Init *>(Range.size()));
276 BitsInit *I = new (Mem) BitsInit(Range.size());
277 std::uninitialized_copy(Range.begin(), Range.end(),
278 I->getTrailingObjects<Init *>());
279 ThePool.InsertNode(I, IP);
280 TheActualPool.push_back(std::unique_ptr<BitsInit>(I));
284 void BitsInit::Profile(FoldingSetNodeID &ID) const {
285 ProfileBitsInit(ID, makeArrayRef(getTrailingObjects<Init *>(), NumBits));
288 Init *BitsInit::convertInitializerTo(RecTy *Ty) const {
289 if (isa<BitRecTy>(Ty)) {
290 if (getNumBits() != 1) return nullptr; // Only accept if just one bit!
294 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
295 // If the number of bits is right, return it. Otherwise we need to expand
297 if (getNumBits() != BRT->getNumBits()) return nullptr;
298 return const_cast<BitsInit *>(this);
301 if (isa<IntRecTy>(Ty)) {
303 for (unsigned i = 0, e = getNumBits(); i != e; ++i)
304 if (auto *Bit = dyn_cast<BitInit>(getBit(i)))
305 Result |= static_cast<int64_t>(Bit->getValue()) << i;
308 return IntInit::get(Result);
315 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
316 SmallVector<Init *, 16> NewBits(Bits.size());
318 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
319 if (Bits[i] >= getNumBits())
321 NewBits[i] = getBit(Bits[i]);
323 return BitsInit::get(NewBits);
326 std::string BitsInit::getAsString() const {
327 std::string Result = "{ ";
328 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
329 if (i) Result += ", ";
330 if (Init *Bit = getBit(e-i-1))
331 Result += Bit->getAsString();
335 return Result + " }";
338 // Fix bit initializer to preserve the behavior that bit reference from a unset
339 // bits initializer will resolve into VarBitInit to keep the field name and bit
340 // number used in targets with fixed insn length.
341 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
342 if (RV || !isa<UnsetInit>(After))
347 // resolveReferences - If there are any field references that refer to fields
348 // that have been filled in, we can propagate the values now.
350 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
351 bool Changed = false;
352 SmallVector<Init *, 16> NewBits(getNumBits());
354 Init *CachedInit = nullptr;
355 Init *CachedBitVar = nullptr;
356 bool CachedBitVarChanged = false;
358 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
359 Init *CurBit = getBit(i);
360 Init *CurBitVar = CurBit->getBitVar();
364 if (CurBitVar == CachedBitVar) {
365 if (CachedBitVarChanged) {
366 Init *Bit = CachedInit->getBit(CurBit->getBitNum());
367 NewBits[i] = fixBitInit(RV, CurBit, Bit);
371 CachedBitVar = CurBitVar;
372 CachedBitVarChanged = false;
377 CurBitVar = CurBitVar->resolveReferences(R, RV);
378 CachedBitVarChanged |= B != CurBitVar;
379 Changed |= B != CurBitVar;
380 } while (B != CurBitVar);
381 CachedInit = CurBitVar;
383 if (CachedBitVarChanged) {
384 Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
385 NewBits[i] = fixBitInit(RV, CurBit, Bit);
390 return BitsInit::get(NewBits);
392 return const_cast<BitsInit *>(this);
395 IntInit *IntInit::get(int64_t V) {
396 static DenseMap<int64_t, std::unique_ptr<IntInit>> ThePool;
398 std::unique_ptr<IntInit> &I = ThePool[V];
399 if (!I) I.reset(new IntInit(V));
403 std::string IntInit::getAsString() const {
404 return itostr(Value);
407 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
408 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
409 return (NumBits >= sizeof(Value) * 8) ||
410 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
413 Init *IntInit::convertInitializerTo(RecTy *Ty) const {
414 if (isa<IntRecTy>(Ty))
415 return const_cast<IntInit *>(this);
417 if (isa<BitRecTy>(Ty)) {
418 int64_t Val = getValue();
419 if (Val != 0 && Val != 1) return nullptr; // Only accept 0 or 1 for a bit!
420 return BitInit::get(Val != 0);
423 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
424 int64_t Value = getValue();
425 // Make sure this bitfield is large enough to hold the integer value.
426 if (!canFitInBitfield(Value, BRT->getNumBits()))
429 SmallVector<Init *, 16> NewBits(BRT->getNumBits());
430 for (unsigned i = 0; i != BRT->getNumBits(); ++i)
431 NewBits[i] = BitInit::get(Value & (1LL << i));
433 return BitsInit::get(NewBits);
440 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
441 SmallVector<Init *, 16> NewBits(Bits.size());
443 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
447 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
449 return BitsInit::get(NewBits);
452 CodeInit *CodeInit::get(StringRef V) {
453 static StringMap<std::unique_ptr<CodeInit>> ThePool;
455 std::unique_ptr<CodeInit> &I = ThePool[V];
456 if (!I) I.reset(new CodeInit(V));
460 StringInit *StringInit::get(StringRef V) {
461 static StringMap<std::unique_ptr<StringInit>> ThePool;
463 std::unique_ptr<StringInit> &I = ThePool[V];
464 if (!I) I.reset(new StringInit(V));
468 Init *StringInit::convertInitializerTo(RecTy *Ty) const {
469 if (isa<StringRecTy>(Ty))
470 return const_cast<StringInit *>(this);
475 Init *CodeInit::convertInitializerTo(RecTy *Ty) const {
476 if (isa<CodeRecTy>(Ty))
477 return const_cast<CodeInit *>(this);
482 static void ProfileListInit(FoldingSetNodeID &ID,
483 ArrayRef<Init *> Range,
485 ID.AddInteger(Range.size());
486 ID.AddPointer(EltTy);
488 for (Init *I : Range)
492 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
493 static FoldingSet<ListInit> ThePool;
494 static std::vector<std::unique_ptr<ListInit>> TheActualPool;
497 ProfileListInit(ID, Range, EltTy);
500 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
503 void *Mem = ::operator new (totalSizeToAlloc<Init *>(Range.size()));
504 ListInit *I = new (Mem) ListInit(Range.size(), EltTy);
505 std::uninitialized_copy(Range.begin(), Range.end(),
506 I->getTrailingObjects<Init *>());
507 ThePool.InsertNode(I, IP);
508 TheActualPool.push_back(std::unique_ptr<ListInit>(I));
512 void ListInit::Profile(FoldingSetNodeID &ID) const {
513 RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
515 ProfileListInit(ID, getValues(), EltTy);
518 Init *ListInit::convertInitializerTo(RecTy *Ty) const {
519 if (auto *LRT = dyn_cast<ListRecTy>(Ty)) {
520 std::vector<Init*> Elements;
522 // Verify that all of the elements of the list are subclasses of the
523 // appropriate class!
524 for (Init *I : getValues())
525 if (Init *CI = I->convertInitializerTo(LRT->getElementType()))
526 Elements.push_back(CI);
530 if (isa<ListRecTy>(getType()))
531 return ListInit::get(Elements, Ty);
538 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
539 std::vector<Init*> Vals;
540 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
541 if (Elements[i] >= size())
543 Vals.push_back(getElement(Elements[i]));
545 return ListInit::get(Vals, getType());
548 Record *ListInit::getElementAsRecord(unsigned i) const {
549 assert(i < NumValues && "List element index out of range!");
550 DefInit *DI = dyn_cast<DefInit>(getElement(i));
552 PrintFatalError("Expected record in list!");
556 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
557 std::vector<Init*> Resolved;
558 Resolved.reserve(size());
559 bool Changed = false;
561 for (Init *CurElt : getValues()) {
566 CurElt = CurElt->resolveReferences(R, RV);
567 Changed |= E != CurElt;
568 } while (E != CurElt);
569 Resolved.push_back(E);
573 return ListInit::get(Resolved, getType());
574 return const_cast<ListInit *>(this);
577 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
578 unsigned Elt) const {
580 return nullptr; // Out of range reference.
581 Init *E = getElement(Elt);
582 // If the element is set to some value, or if we are resolving a reference
583 // to a specific variable and that variable is explicitly unset, then
584 // replace the VarListElementInit with it.
585 if (IRV || !isa<UnsetInit>(E))
590 std::string ListInit::getAsString() const {
591 std::string Result = "[";
592 for (unsigned i = 0, e = NumValues; i != e; ++i) {
593 if (i) Result += ", ";
594 Result += getElement(i)->getAsString();
599 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
600 unsigned Elt) const {
601 Init *Resolved = resolveReferences(R, IRV);
602 OpInit *OResolved = dyn_cast<OpInit>(Resolved);
604 Resolved = OResolved->Fold(&R, nullptr);
607 if (Resolved != this) {
608 TypedInit *Typed = cast<TypedInit>(Resolved);
609 if (Init *New = Typed->resolveListElementReference(R, IRV, Elt))
611 return VarListElementInit::get(Typed, Elt);
617 Init *OpInit::getBit(unsigned Bit) const {
618 if (getType() == BitRecTy::get())
619 return const_cast<OpInit*>(this);
620 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
624 ProfileUnOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *Op, RecTy *Type) {
625 ID.AddInteger(Opcode);
630 UnOpInit *UnOpInit::get(UnaryOp Opc, Init *LHS, RecTy *Type) {
631 static FoldingSet<UnOpInit> ThePool;
632 static std::vector<std::unique_ptr<UnOpInit>> TheActualPool;
635 ProfileUnOpInit(ID, Opc, LHS, Type);
638 if (UnOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
641 UnOpInit *I = new UnOpInit(Opc, LHS, Type);
642 ThePool.InsertNode(I, IP);
643 TheActualPool.push_back(std::unique_ptr<UnOpInit>(I));
647 void UnOpInit::Profile(FoldingSetNodeID &ID) const {
648 ProfileUnOpInit(ID, getOpcode(), getOperand(), getType());
651 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
652 switch (getOpcode()) {
654 if (isa<StringRecTy>(getType())) {
655 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
658 if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
659 return StringInit::get(LHSd->getAsString());
661 if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
662 return StringInit::get(LHSi->getAsString());
664 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
665 const std::string &Name = LHSs->getValue();
667 // From TGParser::ParseIDValue
669 if (const RecordVal *RV = CurRec->getValue(Name)) {
670 if (RV->getType() != getType())
671 PrintFatalError("type mismatch in cast");
672 return VarInit::get(Name, RV->getType());
675 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
678 if (CurRec->isTemplateArg(TemplateArgName)) {
679 const RecordVal *RV = CurRec->getValue(TemplateArgName);
680 assert(RV && "Template arg doesn't exist??");
682 if (RV->getType() != getType())
683 PrintFatalError("type mismatch in cast");
685 return VarInit::get(TemplateArgName, RV->getType());
690 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
693 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
694 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
695 assert(RV && "Template arg doesn't exist??");
697 if (RV->getType() != getType())
698 PrintFatalError("type mismatch in cast");
700 return VarInit::get(MCName, RV->getType());
703 assert(CurRec && "NULL pointer");
704 if (Record *D = (CurRec->getRecords()).getDef(Name))
705 return DefInit::get(D);
707 PrintFatalError(CurRec->getLoc(),
708 "Undefined reference:'" + Name + "'\n");
711 if (isa<IntRecTy>(getType())) {
712 if (BitsInit *BI = dyn_cast<BitsInit>(LHS)) {
713 if (Init *NewInit = BI->convertInitializerTo(IntRecTy::get()))
722 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
723 assert(!LHSl->empty() && "Empty list in head");
724 return LHSl->getElement(0);
729 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
730 assert(!LHSl->empty() && "Empty list in tail");
731 // Note the +1. We can't just pass the result of getValues()
733 return ListInit::get(LHSl->getValues().slice(1), LHSl->getType());
738 if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
739 return IntInit::get(LHSl->empty());
740 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
741 return IntInit::get(LHSs->getValue().empty());
746 return const_cast<UnOpInit *>(this);
749 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
750 Init *lhs = LHS->resolveReferences(R, RV);
753 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, nullptr);
754 return Fold(&R, nullptr);
757 std::string UnOpInit::getAsString() const {
759 switch (getOpcode()) {
760 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
761 case HEAD: Result = "!head"; break;
762 case TAIL: Result = "!tail"; break;
763 case EMPTY: Result = "!empty"; break;
765 return Result + "(" + LHS->getAsString() + ")";
769 ProfileBinOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *RHS,
771 ID.AddInteger(Opcode);
777 BinOpInit *BinOpInit::get(BinaryOp Opc, Init *LHS,
778 Init *RHS, RecTy *Type) {
779 static FoldingSet<BinOpInit> ThePool;
780 static std::vector<std::unique_ptr<BinOpInit>> TheActualPool;
783 ProfileBinOpInit(ID, Opc, LHS, RHS, Type);
786 if (BinOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
789 BinOpInit *I = new BinOpInit(Opc, LHS, RHS, Type);
790 ThePool.InsertNode(I, IP);
791 TheActualPool.push_back(std::unique_ptr<BinOpInit>(I));
795 void BinOpInit::Profile(FoldingSetNodeID &ID) const {
796 ProfileBinOpInit(ID, getOpcode(), getLHS(), getRHS(), getType());
799 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
800 switch (getOpcode()) {
802 DagInit *LHSs = dyn_cast<DagInit>(LHS);
803 DagInit *RHSs = dyn_cast<DagInit>(RHS);
805 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
806 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
807 if (!LOp || !ROp || LOp->getDef() != ROp->getDef())
808 PrintFatalError("Concated Dag operators do not match!");
809 std::vector<Init*> Args;
810 std::vector<std::string> ArgNames;
811 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
812 Args.push_back(LHSs->getArg(i));
813 ArgNames.push_back(LHSs->getArgName(i));
815 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
816 Args.push_back(RHSs->getArg(i));
817 ArgNames.push_back(RHSs->getArgName(i));
819 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
824 ListInit *LHSs = dyn_cast<ListInit>(LHS);
825 ListInit *RHSs = dyn_cast<ListInit>(RHS);
827 std::vector<Init *> Args;
828 Args.insert(Args.end(), LHSs->begin(), LHSs->end());
829 Args.insert(Args.end(), RHSs->begin(), RHSs->end());
830 return ListInit::get(
831 Args, cast<ListRecTy>(LHSs->getType())->getElementType());
836 StringInit *LHSs = dyn_cast<StringInit>(LHS);
837 StringInit *RHSs = dyn_cast<StringInit>(RHS);
839 return StringInit::get(LHSs->getValue() + RHSs->getValue());
843 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
844 // to string objects.
846 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
848 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
851 return IntInit::get(L->getValue() == R->getValue());
853 StringInit *LHSs = dyn_cast<StringInit>(LHS);
854 StringInit *RHSs = dyn_cast<StringInit>(RHS);
856 // Make sure we've resolved
858 return IntInit::get(LHSs->getValue() == RHSs->getValue());
868 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
870 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
872 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
874 switch (getOpcode()) {
875 default: llvm_unreachable("Bad opcode!");
876 case ADD: Result = LHSv + RHSv; break;
877 case AND: Result = LHSv & RHSv; break;
878 case SHL: Result = LHSv << RHSv; break;
879 case SRA: Result = LHSv >> RHSv; break;
880 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
882 return IntInit::get(Result);
887 return const_cast<BinOpInit *>(this);
890 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
891 Init *lhs = LHS->resolveReferences(R, RV);
892 Init *rhs = RHS->resolveReferences(R, RV);
894 if (LHS != lhs || RHS != rhs)
895 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R,nullptr);
896 return Fold(&R, nullptr);
899 std::string BinOpInit::getAsString() const {
901 switch (getOpcode()) {
902 case CONCAT: Result = "!con"; break;
903 case ADD: Result = "!add"; break;
904 case AND: Result = "!and"; break;
905 case SHL: Result = "!shl"; break;
906 case SRA: Result = "!sra"; break;
907 case SRL: Result = "!srl"; break;
908 case EQ: Result = "!eq"; break;
909 case LISTCONCAT: Result = "!listconcat"; break;
910 case STRCONCAT: Result = "!strconcat"; break;
912 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
916 ProfileTernOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *MHS,
917 Init *RHS, RecTy *Type) {
918 ID.AddInteger(Opcode);
925 TernOpInit *TernOpInit::get(TernaryOp Opc, Init *LHS, Init *MHS, Init *RHS,
927 static FoldingSet<TernOpInit> ThePool;
928 static std::vector<std::unique_ptr<TernOpInit>> TheActualPool;
931 ProfileTernOpInit(ID, Opc, LHS, MHS, RHS, Type);
934 if (TernOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
937 TernOpInit *I = new TernOpInit(Opc, LHS, MHS, RHS, Type);
938 ThePool.InsertNode(I, IP);
939 TheActualPool.push_back(std::unique_ptr<TernOpInit>(I));
943 void TernOpInit::Profile(FoldingSetNodeID &ID) const {
944 ProfileTernOpInit(ID, getOpcode(), getLHS(), getMHS(), getRHS(), getType());
947 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
948 Record *CurRec, MultiClass *CurMultiClass);
950 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
951 RecTy *Type, Record *CurRec,
952 MultiClass *CurMultiClass) {
953 // If this is a dag, recurse
954 if (auto *TArg = dyn_cast<TypedInit>(Arg))
955 if (isa<DagRecTy>(TArg->getType()))
956 return ForeachHelper(LHS, Arg, RHSo, Type, CurRec, CurMultiClass);
958 std::vector<Init *> NewOperands;
959 for (unsigned i = 0; i < RHSo->getNumOperands(); ++i) {
960 if (auto *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i))) {
961 if (Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
962 Type, CurRec, CurMultiClass))
963 NewOperands.push_back(Result);
965 NewOperands.push_back(Arg);
966 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
967 NewOperands.push_back(Arg);
969 NewOperands.push_back(RHSo->getOperand(i));
973 // Now run the operator and use its result as the new leaf
974 const OpInit *NewOp = RHSo->clone(NewOperands);
975 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
976 return (NewVal != NewOp) ? NewVal : nullptr;
979 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
980 Record *CurRec, MultiClass *CurMultiClass) {
982 OpInit *RHSo = dyn_cast<OpInit>(RHS);
985 PrintFatalError(CurRec->getLoc(), "!foreach requires an operator\n");
987 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
990 PrintFatalError(CurRec->getLoc(), "!foreach requires typed variable\n");
992 DagInit *MHSd = dyn_cast<DagInit>(MHS);
993 if (MHSd && isa<DagRecTy>(Type)) {
994 Init *Val = MHSd->getOperator();
995 if (Init *Result = EvaluateOperation(RHSo, LHS, Val,
996 Type, CurRec, CurMultiClass))
999 std::vector<std::pair<Init *, std::string> > args;
1000 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1001 Init *Arg = MHSd->getArg(i);
1002 std::string ArgName = MHSd->getArgName(i);
1005 if (Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1006 CurRec, CurMultiClass))
1009 // TODO: Process arg names
1010 args.push_back(std::make_pair(Arg, ArgName));
1013 return DagInit::get(Val, "", args);
1016 ListInit *MHSl = dyn_cast<ListInit>(MHS);
1017 if (MHSl && isa<ListRecTy>(Type)) {
1018 std::vector<Init *> NewOperands;
1019 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1021 for (Init *&Item : NewList) {
1022 NewOperands.clear();
1023 for(unsigned i = 0; i < RHSo->getNumOperands(); ++i) {
1024 // First, replace the foreach variable with the list item
1025 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString())
1026 NewOperands.push_back(Item);
1028 NewOperands.push_back(RHSo->getOperand(i));
1031 // Now run the operator and use its result as the new list item
1032 const OpInit *NewOp = RHSo->clone(NewOperands);
1033 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1034 if (NewItem != NewOp)
1037 return ListInit::get(NewList, MHSl->getType());
1042 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1043 switch (getOpcode()) {
1045 DefInit *LHSd = dyn_cast<DefInit>(LHS);
1046 VarInit *LHSv = dyn_cast<VarInit>(LHS);
1047 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1049 DefInit *MHSd = dyn_cast<DefInit>(MHS);
1050 VarInit *MHSv = dyn_cast<VarInit>(MHS);
1051 StringInit *MHSs = dyn_cast<StringInit>(MHS);
1053 DefInit *RHSd = dyn_cast<DefInit>(RHS);
1054 VarInit *RHSv = dyn_cast<VarInit>(RHS);
1055 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1057 if (LHSd && MHSd && RHSd) {
1058 Record *Val = RHSd->getDef();
1059 if (LHSd->getAsString() == RHSd->getAsString())
1060 Val = MHSd->getDef();
1061 return DefInit::get(Val);
1063 if (LHSv && MHSv && RHSv) {
1064 std::string Val = RHSv->getName();
1065 if (LHSv->getAsString() == RHSv->getAsString())
1066 Val = MHSv->getName();
1067 return VarInit::get(Val, getType());
1069 if (LHSs && MHSs && RHSs) {
1070 std::string Val = RHSs->getValue();
1072 std::string::size_type found;
1073 std::string::size_type idx = 0;
1075 found = Val.find(LHSs->getValue(), idx);
1076 if (found == std::string::npos)
1078 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1079 idx = found + MHSs->getValue().size();
1082 return StringInit::get(Val);
1088 if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1089 CurRec, CurMultiClass))
1095 IntInit *LHSi = dyn_cast<IntInit>(LHS);
1096 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1097 LHSi = dyn_cast<IntInit>(I);
1099 if (LHSi->getValue())
1107 return const_cast<TernOpInit *>(this);
1110 Init *TernOpInit::resolveReferences(Record &R,
1111 const RecordVal *RV) const {
1112 Init *lhs = LHS->resolveReferences(R, RV);
1114 if (getOpcode() == IF && lhs != LHS) {
1115 IntInit *Value = dyn_cast<IntInit>(lhs);
1116 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1117 Value = dyn_cast<IntInit>(I);
1120 if (Value->getValue()) {
1121 Init *mhs = MHS->resolveReferences(R, RV);
1122 return (TernOpInit::get(getOpcode(), lhs, mhs,
1123 RHS, getType()))->Fold(&R, nullptr);
1125 Init *rhs = RHS->resolveReferences(R, RV);
1126 return (TernOpInit::get(getOpcode(), lhs, MHS,
1127 rhs, getType()))->Fold(&R, nullptr);
1131 Init *mhs = MHS->resolveReferences(R, RV);
1132 Init *rhs = RHS->resolveReferences(R, RV);
1134 if (LHS != lhs || MHS != mhs || RHS != rhs)
1135 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1136 getType()))->Fold(&R, nullptr);
1137 return Fold(&R, nullptr);
1140 std::string TernOpInit::getAsString() const {
1142 switch (getOpcode()) {
1143 case SUBST: Result = "!subst"; break;
1144 case FOREACH: Result = "!foreach"; break;
1145 case IF: Result = "!if"; break;
1147 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", " +
1148 RHS->getAsString() + ")";
1151 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1152 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
1153 if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
1154 return Field->getType();
1159 TypedInit::convertInitializerTo(RecTy *Ty) const {
1160 if (isa<IntRecTy>(Ty)) {
1161 if (getType()->typeIsConvertibleTo(Ty))
1162 return const_cast<TypedInit *>(this);
1166 if (isa<StringRecTy>(Ty)) {
1167 if (isa<StringRecTy>(getType()))
1168 return const_cast<TypedInit *>(this);
1172 if (isa<CodeRecTy>(Ty)) {
1173 if (isa<CodeRecTy>(getType()))
1174 return const_cast<TypedInit *>(this);
1178 if (isa<BitRecTy>(Ty)) {
1179 // Accept variable if it is already of bit type!
1180 if (isa<BitRecTy>(getType()))
1181 return const_cast<TypedInit *>(this);
1182 if (auto *BitsTy = dyn_cast<BitsRecTy>(getType())) {
1183 // Accept only bits<1> expression.
1184 if (BitsTy->getNumBits() == 1)
1185 return const_cast<TypedInit *>(this);
1188 // Ternary !if can be converted to bit, but only if both sides are
1189 // convertible to a bit.
1190 if (const auto *TOI = dyn_cast<TernOpInit>(this)) {
1191 if (TOI->getOpcode() == TernOpInit::TernaryOp::IF &&
1192 TOI->getMHS()->convertInitializerTo(BitRecTy::get()) &&
1193 TOI->getRHS()->convertInitializerTo(BitRecTy::get()))
1194 return const_cast<TypedInit *>(this);
1200 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
1201 if (BRT->getNumBits() == 1 && isa<BitRecTy>(getType()))
1202 return BitsInit::get(const_cast<TypedInit *>(this));
1204 if (getType()->typeIsConvertibleTo(BRT)) {
1205 SmallVector<Init *, 16> NewBits(BRT->getNumBits());
1207 for (unsigned i = 0; i != BRT->getNumBits(); ++i)
1208 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), i);
1209 return BitsInit::get(NewBits);
1215 if (auto *DLRT = dyn_cast<ListRecTy>(Ty)) {
1216 if (auto *SLRT = dyn_cast<ListRecTy>(getType()))
1217 if (SLRT->getElementType()->typeIsConvertibleTo(DLRT->getElementType()))
1218 return const_cast<TypedInit *>(this);
1222 if (auto *DRT = dyn_cast<DagRecTy>(Ty)) {
1223 if (getType()->typeIsConvertibleTo(DRT))
1224 return const_cast<TypedInit *>(this);
1228 if (auto *SRRT = dyn_cast<RecordRecTy>(Ty)) {
1229 // Ensure that this is compatible with Rec.
1230 if (RecordRecTy *DRRT = dyn_cast<RecordRecTy>(getType()))
1231 if (DRRT->getRecord()->isSubClassOf(SRRT->getRecord()) ||
1232 DRRT->getRecord() == SRRT->getRecord())
1233 return const_cast<TypedInit *>(this);
1241 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1242 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1243 if (!T) return nullptr; // Cannot subscript a non-bits variable.
1244 unsigned NumBits = T->getNumBits();
1246 SmallVector<Init *, 16> NewBits(Bits.size());
1247 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1248 if (Bits[i] >= NumBits)
1251 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1253 return BitsInit::get(NewBits);
1257 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1258 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1259 if (!T) return nullptr; // Cannot subscript a non-list variable.
1261 if (Elements.size() == 1)
1262 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1264 std::vector<Init*> ListInits;
1265 ListInits.reserve(Elements.size());
1266 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1267 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1269 return ListInit::get(ListInits, T);
1273 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1274 Init *Value = StringInit::get(VN);
1275 return VarInit::get(Value, T);
1278 VarInit *VarInit::get(Init *VN, RecTy *T) {
1279 typedef std::pair<RecTy *, Init *> Key;
1280 static DenseMap<Key, std::unique_ptr<VarInit>> ThePool;
1282 Key TheKey(std::make_pair(T, VN));
1284 std::unique_ptr<VarInit> &I = ThePool[TheKey];
1285 if (!I) I.reset(new VarInit(VN, T));
1289 const std::string &VarInit::getName() const {
1290 StringInit *NameString = cast<StringInit>(getNameInit());
1291 return NameString->getValue();
1294 Init *VarInit::getBit(unsigned Bit) const {
1295 if (getType() == BitRecTy::get())
1296 return const_cast<VarInit*>(this);
1297 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1300 Init *VarInit::resolveListElementReference(Record &R,
1301 const RecordVal *IRV,
1302 unsigned Elt) const {
1303 if (R.isTemplateArg(getNameInit())) return nullptr;
1304 if (IRV && IRV->getNameInit() != getNameInit()) return nullptr;
1306 RecordVal *RV = R.getValue(getNameInit());
1307 assert(RV && "Reference to a non-existent variable?");
1308 ListInit *LI = dyn_cast<ListInit>(RV->getValue());
1310 return VarListElementInit::get(cast<TypedInit>(RV->getValue()), Elt);
1312 if (Elt >= LI->size())
1313 return nullptr; // Out of range reference.
1314 Init *E = LI->getElement(Elt);
1315 // If the element is set to some value, or if we are resolving a reference
1316 // to a specific variable and that variable is explicitly unset, then
1317 // replace the VarListElementInit with it.
1318 if (IRV || !isa<UnsetInit>(E))
1324 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1325 if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
1326 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1327 return RV->getType();
1331 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1332 const std::string &FieldName) const {
1333 if (isa<RecordRecTy>(getType()))
1334 if (const RecordVal *Val = R.getValue(VarName)) {
1335 if (RV != Val && (RV || isa<UnsetInit>(Val->getValue())))
1337 Init *TheInit = Val->getValue();
1338 assert(TheInit != this && "Infinite loop detected!");
1339 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1346 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1347 if (RecordVal *Val = R.getValue(VarName))
1348 if (RV == Val || (!RV && !isa<UnsetInit>(Val->getValue())))
1349 return Val->getValue();
1350 return const_cast<VarInit *>(this);
1353 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1354 typedef std::pair<TypedInit *, unsigned> Key;
1355 static DenseMap<Key, std::unique_ptr<VarBitInit>> ThePool;
1357 Key TheKey(std::make_pair(T, B));
1359 std::unique_ptr<VarBitInit> &I = ThePool[TheKey];
1360 if (!I) I.reset(new VarBitInit(T, B));
1364 Init *VarBitInit::convertInitializerTo(RecTy *Ty) const {
1365 if (isa<BitRecTy>(Ty))
1366 return const_cast<VarBitInit *>(this);
1371 std::string VarBitInit::getAsString() const {
1372 return TI->getAsString() + "{" + utostr(Bit) + "}";
1375 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1376 Init *I = TI->resolveReferences(R, RV);
1378 return I->getBit(getBitNum());
1380 return const_cast<VarBitInit*>(this);
1383 VarListElementInit *VarListElementInit::get(TypedInit *T,
1385 typedef std::pair<TypedInit *, unsigned> Key;
1386 static DenseMap<Key, std::unique_ptr<VarListElementInit>> ThePool;
1388 Key TheKey(std::make_pair(T, E));
1390 std::unique_ptr<VarListElementInit> &I = ThePool[TheKey];
1391 if (!I) I.reset(new VarListElementInit(T, E));
1395 std::string VarListElementInit::getAsString() const {
1396 return TI->getAsString() + "[" + utostr(Element) + "]";
1400 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1401 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1404 return const_cast<VarListElementInit *>(this);
1407 Init *VarListElementInit::getBit(unsigned Bit) const {
1408 if (getType() == BitRecTy::get())
1409 return const_cast<VarListElementInit*>(this);
1410 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1413 Init *VarListElementInit:: resolveListElementReference(Record &R,
1414 const RecordVal *RV,
1415 unsigned Elt) const {
1416 if (Init *Result = TI->resolveListElementReference(R, RV, Element)) {
1417 if (TypedInit *TInit = dyn_cast<TypedInit>(Result)) {
1418 if (Init *Result2 = TInit->resolveListElementReference(R, RV, Elt))
1420 return VarListElementInit::get(TInit, Elt);
1428 DefInit *DefInit::get(Record *R) {
1429 return R->getDefInit();
1432 Init *DefInit::convertInitializerTo(RecTy *Ty) const {
1433 if (auto *RRT = dyn_cast<RecordRecTy>(Ty))
1434 if (getDef()->isSubClassOf(RRT->getRecord()))
1435 return const_cast<DefInit *>(this);
1439 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1440 if (const RecordVal *RV = Def->getValue(FieldName))
1441 return RV->getType();
1445 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1446 const std::string &FieldName) const {
1447 return Def->getValue(FieldName)->getValue();
1451 std::string DefInit::getAsString() const {
1452 return Def->getName();
1455 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1456 typedef std::pair<Init *, TableGenStringKey> Key;
1457 static DenseMap<Key, std::unique_ptr<FieldInit>> ThePool;
1459 Key TheKey(std::make_pair(R, FN));
1461 std::unique_ptr<FieldInit> &I = ThePool[TheKey];
1462 if (!I) I.reset(new FieldInit(R, FN));
1466 Init *FieldInit::getBit(unsigned Bit) const {
1467 if (getType() == BitRecTy::get())
1468 return const_cast<FieldInit*>(this);
1469 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1472 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1473 unsigned Elt) const {
1474 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1475 if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
1476 if (Elt >= LI->size()) return nullptr;
1477 Init *E = LI->getElement(Elt);
1479 // If the element is set to some value, or if we are resolving a
1480 // reference to a specific variable and that variable is explicitly
1481 // unset, then replace the VarListElementInit with it.
1482 if (RV || !isa<UnsetInit>(E))
1488 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1489 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1491 if (Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName)) {
1492 Init *BVR = BitsVal->resolveReferences(R, RV);
1493 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1497 return FieldInit::get(NewRec, FieldName);
1498 return const_cast<FieldInit *>(this);
1501 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, const std::string &VN,
1502 ArrayRef<Init *> ArgRange,
1503 ArrayRef<std::string> NameRange) {
1507 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1508 ArrayRef<std::string>::iterator Name = NameRange.begin();
1509 while (Arg != ArgRange.end()) {
1510 assert(Name != NameRange.end() && "Arg name underflow!");
1511 ID.AddPointer(*Arg++);
1512 ID.AddString(*Name++);
1514 assert(Name == NameRange.end() && "Arg name overflow!");
1518 DagInit::get(Init *V, const std::string &VN,
1519 ArrayRef<Init *> ArgRange,
1520 ArrayRef<std::string> NameRange) {
1521 static FoldingSet<DagInit> ThePool;
1522 static std::vector<std::unique_ptr<DagInit>> TheActualPool;
1524 FoldingSetNodeID ID;
1525 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1528 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1531 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1532 ThePool.InsertNode(I, IP);
1533 TheActualPool.push_back(std::unique_ptr<DagInit>(I));
1538 DagInit::get(Init *V, const std::string &VN,
1539 const std::vector<std::pair<Init*, std::string> > &args) {
1540 std::vector<Init *> Args;
1541 std::vector<std::string> Names;
1543 for (const auto &Arg : args) {
1544 Args.push_back(Arg.first);
1545 Names.push_back(Arg.second);
1548 return DagInit::get(V, VN, Args, Names);
1551 void DagInit::Profile(FoldingSetNodeID &ID) const {
1552 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1555 Init *DagInit::convertInitializerTo(RecTy *Ty) const {
1556 if (isa<DagRecTy>(Ty))
1557 return const_cast<DagInit *>(this);
1562 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1563 std::vector<Init*> NewArgs;
1564 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1565 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1567 Init *Op = Val->resolveReferences(R, RV);
1569 if (Args != NewArgs || Op != Val)
1570 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1572 return const_cast<DagInit *>(this);
1576 std::string DagInit::getAsString() const {
1577 std::string Result = "(" + Val->getAsString();
1578 if (!ValName.empty())
1579 Result += ":" + ValName;
1580 if (!Args.empty()) {
1581 Result += " " + Args[0]->getAsString();
1582 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1583 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1584 Result += ", " + Args[i]->getAsString();
1585 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1588 return Result + ")";
1592 //===----------------------------------------------------------------------===//
1593 // Other implementations
1594 //===----------------------------------------------------------------------===//
1596 RecordVal::RecordVal(Init *N, RecTy *T, bool P)
1597 : NameAndPrefix(N, P), Ty(T) {
1598 Value = UnsetInit::get()->convertInitializerTo(Ty);
1599 assert(Value && "Cannot create unset value for current type!");
1602 RecordVal::RecordVal(const std::string &N, RecTy *T, bool P)
1603 : NameAndPrefix(StringInit::get(N), P), Ty(T) {
1604 Value = UnsetInit::get()->convertInitializerTo(Ty);
1605 assert(Value && "Cannot create unset value for current type!");
1608 const std::string &RecordVal::getName() const {
1609 return cast<StringInit>(getNameInit())->getValue();
1612 LLVM_DUMP_METHOD void RecordVal::dump() const { errs() << *this; }
1614 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1615 if (getPrefix()) OS << "field ";
1616 OS << *getType() << " " << getNameInitAsString();
1619 OS << " = " << *getValue();
1621 if (PrintSem) OS << ";\n";
1624 unsigned Record::LastID = 0;
1626 void Record::init() {
1629 // Every record potentially has a def at the top. This value is
1630 // replaced with the top-level def name at instantiation time.
1631 RecordVal DN("NAME", StringRecTy::get(), 0);
1635 void Record::checkName() {
1636 // Ensure the record name has string type.
1637 const TypedInit *TypedName = cast<const TypedInit>(Name);
1638 if (!isa<StringRecTy>(TypedName->getType()))
1639 PrintFatalError(getLoc(), "Record name is not a string!");
1642 DefInit *Record::getDefInit() {
1644 TheInit.reset(new DefInit(this, new RecordRecTy(this)));
1645 return TheInit.get();
1648 const std::string &Record::getName() const {
1649 return cast<StringInit>(Name)->getValue();
1652 void Record::setName(Init *NewName) {
1655 // DO NOT resolve record values to the name at this point because
1656 // there might be default values for arguments of this def. Those
1657 // arguments might not have been resolved yet so we don't want to
1658 // prematurely assume values for those arguments were not passed to
1661 // Nonetheless, it may be that some of this Record's values
1662 // reference the record name. Indeed, the reason for having the
1663 // record name be an Init is to provide this flexibility. The extra
1664 // resolve steps after completely instantiating defs takes care of
1665 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1668 void Record::setName(const std::string &Name) {
1669 setName(StringInit::get(Name));
1672 void Record::resolveReferencesTo(const RecordVal *RV) {
1673 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1674 if (RV == &Values[i]) // Skip resolve the same field as the given one
1676 if (Init *V = Values[i].getValue())
1677 if (Values[i].setValue(V->resolveReferences(*this, RV)))
1678 PrintFatalError(getLoc(), "Invalid value is found when setting '" +
1679 Values[i].getNameInitAsString() +
1680 "' after resolving references" +
1681 (RV ? " against '" + RV->getNameInitAsString() +
1682 "' of (" + RV->getValue()->getAsUnquotedString() +
1686 Init *OldName = getNameInit();
1687 Init *NewName = Name->resolveReferences(*this, RV);
1688 if (NewName != OldName) {
1689 // Re-register with RecordKeeper.
1694 LLVM_DUMP_METHOD void Record::dump() const { errs() << *this; }
1696 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1697 OS << R.getNameInitAsString();
1699 ArrayRef<Init *> TArgs = R.getTemplateArgs();
1700 if (!TArgs.empty()) {
1702 bool NeedComma = false;
1703 for (const Init *TA : TArgs) {
1704 if (NeedComma) OS << ", ";
1706 const RecordVal *RV = R.getValue(TA);
1707 assert(RV && "Template argument record not found??");
1708 RV->print(OS, false);
1714 ArrayRef<std::pair<Record *, SMRange>> SC = R.getSuperClasses();
1717 for (const auto &SuperPair : SC)
1718 OS << " " << SuperPair.first->getNameInitAsString();
1722 for (const RecordVal &Val : R.getValues())
1723 if (Val.getPrefix() && !R.isTemplateArg(Val.getName()))
1725 for (const RecordVal &Val : R.getValues())
1726 if (!Val.getPrefix() && !R.isTemplateArg(Val.getName()))
1732 Init *Record::getValueInit(StringRef FieldName) const {
1733 const RecordVal *R = getValue(FieldName);
1734 if (!R || !R->getValue())
1735 PrintFatalError(getLoc(), "Record `" + getName() +
1736 "' does not have a field named `" + FieldName + "'!\n");
1737 return R->getValue();
1741 std::string Record::getValueAsString(StringRef FieldName) const {
1742 const RecordVal *R = getValue(FieldName);
1743 if (!R || !R->getValue())
1744 PrintFatalError(getLoc(), "Record `" + getName() +
1745 "' does not have a field named `" + FieldName + "'!\n");
1747 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1748 return SI->getValue();
1749 if (CodeInit *CI = dyn_cast<CodeInit>(R->getValue()))
1750 return CI->getValue();
1752 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1753 FieldName + "' does not have a string initializer!");
1756 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1757 const RecordVal *R = getValue(FieldName);
1758 if (!R || !R->getValue())
1759 PrintFatalError(getLoc(), "Record `" + getName() +
1760 "' does not have a field named `" + FieldName + "'!\n");
1762 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
1764 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1765 FieldName + "' does not have a BitsInit initializer!");
1768 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1769 const RecordVal *R = getValue(FieldName);
1770 if (!R || !R->getValue())
1771 PrintFatalError(getLoc(), "Record `" + getName() +
1772 "' does not have a field named `" + FieldName + "'!\n");
1774 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
1776 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1777 FieldName + "' does not have a list initializer!");
1780 std::vector<Record*>
1781 Record::getValueAsListOfDefs(StringRef FieldName) const {
1782 ListInit *List = getValueAsListInit(FieldName);
1783 std::vector<Record*> Defs;
1784 for (Init *I : List->getValues()) {
1785 if (DefInit *DI = dyn_cast<DefInit>(I))
1786 Defs.push_back(DI->getDef());
1788 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1789 FieldName + "' list is not entirely DefInit!");
1794 int64_t Record::getValueAsInt(StringRef FieldName) const {
1795 const RecordVal *R = getValue(FieldName);
1796 if (!R || !R->getValue())
1797 PrintFatalError(getLoc(), "Record `" + getName() +
1798 "' does not have a field named `" + FieldName + "'!\n");
1800 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
1801 return II->getValue();
1802 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1803 FieldName + "' does not have an int initializer!");
1806 std::vector<int64_t>
1807 Record::getValueAsListOfInts(StringRef FieldName) const {
1808 ListInit *List = getValueAsListInit(FieldName);
1809 std::vector<int64_t> Ints;
1810 for (Init *I : List->getValues()) {
1811 if (IntInit *II = dyn_cast<IntInit>(I))
1812 Ints.push_back(II->getValue());
1814 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1815 FieldName + "' does not have a list of ints initializer!");
1820 std::vector<std::string>
1821 Record::getValueAsListOfStrings(StringRef FieldName) const {
1822 ListInit *List = getValueAsListInit(FieldName);
1823 std::vector<std::string> Strings;
1824 for (Init *I : List->getValues()) {
1825 if (StringInit *SI = dyn_cast<StringInit>(I))
1826 Strings.push_back(SI->getValue());
1828 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1829 FieldName + "' does not have a list of strings initializer!");
1834 Record *Record::getValueAsDef(StringRef FieldName) const {
1835 const RecordVal *R = getValue(FieldName);
1836 if (!R || !R->getValue())
1837 PrintFatalError(getLoc(), "Record `" + getName() +
1838 "' does not have a field named `" + FieldName + "'!\n");
1840 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
1841 return DI->getDef();
1842 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1843 FieldName + "' does not have a def initializer!");
1846 bool Record::getValueAsBit(StringRef FieldName) const {
1847 const RecordVal *R = getValue(FieldName);
1848 if (!R || !R->getValue())
1849 PrintFatalError(getLoc(), "Record `" + getName() +
1850 "' does not have a field named `" + FieldName + "'!\n");
1852 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1853 return BI->getValue();
1854 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1855 FieldName + "' does not have a bit initializer!");
1858 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1859 const RecordVal *R = getValue(FieldName);
1860 if (!R || !R->getValue())
1861 PrintFatalError(getLoc(), "Record `" + getName() +
1862 "' does not have a field named `" + FieldName.str() + "'!\n");
1864 if (isa<UnsetInit>(R->getValue())) {
1869 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1870 return BI->getValue();
1871 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1872 FieldName + "' does not have a bit initializer!");
1875 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1876 const RecordVal *R = getValue(FieldName);
1877 if (!R || !R->getValue())
1878 PrintFatalError(getLoc(), "Record `" + getName() +
1879 "' does not have a field named `" + FieldName + "'!\n");
1881 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
1883 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1884 FieldName + "' does not have a dag initializer!");
1888 LLVM_DUMP_METHOD void MultiClass::dump() const {
1889 errs() << "Record:\n";
1892 errs() << "Defs:\n";
1893 for (const auto &Proto : DefPrototypes)
1898 LLVM_DUMP_METHOD void RecordKeeper::dump() const { errs() << *this; }
1900 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1901 OS << "------------- Classes -----------------\n";
1902 for (const auto &C : RK.getClasses())
1903 OS << "class " << *C.second;
1905 OS << "------------- Defs -----------------\n";
1906 for (const auto &D : RK.getDefs())
1907 OS << "def " << *D.second;
1911 std::vector<Record *>
1912 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
1913 Record *Class = getClass(ClassName);
1915 PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
1917 std::vector<Record*> Defs;
1918 for (const auto &D : getDefs())
1919 if (D.second->isSubClassOf(Class))
1920 Defs.push_back(D.second.get());
1925 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1926 Init *Name, const std::string &Scoper) {
1927 RecTy *Type = cast<TypedInit>(Name)->getType();
1929 BinOpInit *NewName =
1930 BinOpInit::get(BinOpInit::STRCONCAT,
1931 BinOpInit::get(BinOpInit::STRCONCAT,
1932 CurRec.getNameInit(),
1933 StringInit::get(Scoper),
1934 Type)->Fold(&CurRec, CurMultiClass),
1938 if (CurMultiClass && Scoper != "::") {
1940 BinOpInit::get(BinOpInit::STRCONCAT,
1941 BinOpInit::get(BinOpInit::STRCONCAT,
1942 CurMultiClass->Rec.getNameInit(),
1943 StringInit::get("::"),
1944 Type)->Fold(&CurRec, CurMultiClass),
1945 NewName->Fold(&CurRec, CurMultiClass),
1949 return NewName->Fold(&CurRec, CurMultiClass);
1952 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1953 const std::string &Name,
1954 const std::string &Scoper) {
1955 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);