1 //===- Record.cpp - Record implementation ---------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implement the tablegen record classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/TableGen/Record.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/FoldingSet.h"
17 #include "llvm/ADT/Hashing.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/Support/DataTypes.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/Format.h"
25 #include "llvm/TableGen/Error.h"
29 //===----------------------------------------------------------------------===//
30 // std::string wrapper for DenseMap purposes
31 //===----------------------------------------------------------------------===//
35 /// TableGenStringKey - This is a wrapper for std::string suitable for
36 /// using as a key to a DenseMap. Because there isn't a particularly
37 /// good way to indicate tombstone or empty keys for strings, we want
38 /// to wrap std::string to indicate that this is a "special" string
39 /// not expected to take on certain values (those of the tombstone and
40 /// empty keys). This makes things a little safer as it clarifies
41 /// that DenseMap is really not appropriate for general strings.
43 class TableGenStringKey {
45 TableGenStringKey(const std::string &str) : data(str) {}
46 TableGenStringKey(const char *str) : data(str) {}
48 const std::string &str() const { return data; }
50 friend hash_code hash_value(const TableGenStringKey &Value) {
51 using llvm::hash_value;
52 return hash_value(Value.str());
58 /// Specialize DenseMapInfo for TableGenStringKey.
59 template<> struct DenseMapInfo<TableGenStringKey> {
60 static inline TableGenStringKey getEmptyKey() {
61 TableGenStringKey Empty("<<<EMPTY KEY>>>");
64 static inline TableGenStringKey getTombstoneKey() {
65 TableGenStringKey Tombstone("<<<TOMBSTONE KEY>>>");
68 static unsigned getHashValue(const TableGenStringKey& Val) {
69 using llvm::hash_value;
70 return hash_value(Val);
72 static bool isEqual(const TableGenStringKey& LHS,
73 const TableGenStringKey& RHS) {
74 return LHS.str() == RHS.str();
80 //===----------------------------------------------------------------------===//
81 // Type implementations
82 //===----------------------------------------------------------------------===//
84 BitRecTy BitRecTy::Shared;
85 IntRecTy IntRecTy::Shared;
86 StringRecTy StringRecTy::Shared;
87 DagRecTy DagRecTy::Shared;
89 void RecTy::anchor() { }
90 void RecTy::dump() const { print(errs()); }
92 ListRecTy *RecTy::getListTy() {
94 ListTy = new ListRecTy(this);
98 bool RecTy::baseClassOf(const RecTy *RHS) const{
99 assert (RHS && "NULL pointer");
100 return Kind == RHS->getRecTyKind();
103 Init *BitRecTy::convertValue(BitsInit *BI) {
104 if (BI->getNumBits() != 1) return nullptr; // Only accept if just one bit!
105 return BI->getBit(0);
108 Init *BitRecTy::convertValue(IntInit *II) {
109 int64_t Val = II->getValue();
110 if (Val != 0 && Val != 1) return nullptr; // Only accept 0 or 1 for a bit!
112 return BitInit::get(Val != 0);
115 Init *BitRecTy::convertValue(TypedInit *VI) {
116 RecTy *Ty = VI->getType();
117 if (isa<BitRecTy>(Ty))
118 return VI; // Accept variable if it is already of bit type!
119 if (auto *BitsTy = dyn_cast<BitsRecTy>(Ty))
120 // Accept only bits<1> expression.
121 return BitsTy->getNumBits() == 1 ? VI : nullptr;
122 // Ternary !if can be converted to bit, but only if both sides are
123 // convertible to a bit.
124 if (TernOpInit *TOI = dyn_cast<TernOpInit>(VI)) {
125 if (TOI->getOpcode() != TernOpInit::TernaryOp::IF)
127 if (!TOI->getMHS()->convertInitializerTo(BitRecTy::get()) ||
128 !TOI->getRHS()->convertInitializerTo(BitRecTy::get()))
135 bool BitRecTy::baseClassOf(const RecTy *RHS) const{
136 if(RecTy::baseClassOf(RHS) || getRecTyKind() == IntRecTyKind)
138 if(const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
139 return BitsTy->getNumBits() == 1;
143 BitsRecTy *BitsRecTy::get(unsigned Sz) {
144 static std::vector<BitsRecTy*> Shared;
145 if (Sz >= Shared.size())
146 Shared.resize(Sz + 1);
147 BitsRecTy *&Ty = Shared[Sz];
149 Ty = new BitsRecTy(Sz);
153 std::string BitsRecTy::getAsString() const {
154 return "bits<" + utostr(Size) + ">";
157 Init *BitsRecTy::convertValue(UnsetInit *UI) {
158 SmallVector<Init *, 16> NewBits(Size);
160 for (unsigned i = 0; i != Size; ++i)
161 NewBits[i] = UnsetInit::get();
163 return BitsInit::get(NewBits);
166 Init *BitsRecTy::convertValue(BitInit *UI) {
167 if (Size != 1) return nullptr; // Can only convert single bit.
168 return BitsInit::get(UI);
171 /// canFitInBitfield - Return true if the number of bits is large enough to hold
172 /// the integer value.
173 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
174 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
175 return (NumBits >= sizeof(Value) * 8) ||
176 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
179 /// convertValue from Int initializer to bits type: Split the integer up into the
180 /// appropriate bits.
182 Init *BitsRecTy::convertValue(IntInit *II) {
183 int64_t Value = II->getValue();
184 // Make sure this bitfield is large enough to hold the integer value.
185 if (!canFitInBitfield(Value, Size))
188 SmallVector<Init *, 16> NewBits(Size);
190 for (unsigned i = 0; i != Size; ++i)
191 NewBits[i] = BitInit::get(Value & (1LL << i));
193 return BitsInit::get(NewBits);
196 Init *BitsRecTy::convertValue(BitsInit *BI) {
197 // If the number of bits is right, return it. Otherwise we need to expand or
199 if (BI->getNumBits() == Size) return BI;
203 Init *BitsRecTy::convertValue(TypedInit *VI) {
204 if (Size == 1 && isa<BitRecTy>(VI->getType()))
205 return BitsInit::get(VI);
207 if (VI->getType()->typeIsConvertibleTo(this)) {
208 SmallVector<Init *, 16> NewBits(Size);
210 for (unsigned i = 0; i != Size; ++i)
211 NewBits[i] = VarBitInit::get(VI, i);
212 return BitsInit::get(NewBits);
218 bool BitsRecTy::baseClassOf(const RecTy *RHS) const{
219 if (RecTy::baseClassOf(RHS)) //argument and the receiver are the same type
220 return cast<BitsRecTy>(RHS)->Size == Size;
221 RecTyKind kind = RHS->getRecTyKind();
222 return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
225 Init *IntRecTy::convertValue(BitInit *BI) {
226 return IntInit::get(BI->getValue());
229 Init *IntRecTy::convertValue(BitsInit *BI) {
231 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
232 if (BitInit *Bit = dyn_cast<BitInit>(BI->getBit(i))) {
233 Result |= Bit->getValue() << i;
237 return IntInit::get(Result);
240 Init *IntRecTy::convertValue(TypedInit *TI) {
241 if (TI->getType()->typeIsConvertibleTo(this))
242 return TI; // Accept variable if already of the right type!
246 bool IntRecTy::baseClassOf(const RecTy *RHS) const{
247 RecTyKind kind = RHS->getRecTyKind();
248 return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
251 Init *StringRecTy::convertValue(UnOpInit *BO) {
252 if (BO->getOpcode() == UnOpInit::CAST) {
253 Init *L = BO->getOperand()->convertInitializerTo(this);
254 if (!L) return nullptr;
255 if (L != BO->getOperand())
256 return UnOpInit::get(UnOpInit::CAST, L, new StringRecTy);
260 return convertValue((TypedInit*)BO);
263 Init *StringRecTy::convertValue(BinOpInit *BO) {
264 if (BO->getOpcode() == BinOpInit::STRCONCAT) {
265 Init *L = BO->getLHS()->convertInitializerTo(this);
266 Init *R = BO->getRHS()->convertInitializerTo(this);
267 if (!L || !R) return nullptr;
268 if (L != BO->getLHS() || R != BO->getRHS())
269 return BinOpInit::get(BinOpInit::STRCONCAT, L, R, new StringRecTy);
273 return convertValue((TypedInit*)BO);
277 Init *StringRecTy::convertValue(TypedInit *TI) {
278 if (isa<StringRecTy>(TI->getType()))
279 return TI; // Accept variable if already of the right type!
283 std::string ListRecTy::getAsString() const {
284 return "list<" + Ty->getAsString() + ">";
287 Init *ListRecTy::convertValue(ListInit *LI) {
288 std::vector<Init*> Elements;
290 // Verify that all of the elements of the list are subclasses of the
291 // appropriate class!
292 for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
293 if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
294 Elements.push_back(CI);
298 if (!isa<ListRecTy>(LI->getType()))
301 return ListInit::get(Elements, this);
304 Init *ListRecTy::convertValue(TypedInit *TI) {
305 // Ensure that TI is compatible with our class.
306 if (ListRecTy *LRT = dyn_cast<ListRecTy>(TI->getType()))
307 if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
312 bool ListRecTy::baseClassOf(const RecTy *RHS) const{
313 if(const ListRecTy* ListTy = dyn_cast<ListRecTy>(RHS))
314 return ListTy->getElementType()->typeIsConvertibleTo(Ty);
318 Init *DagRecTy::convertValue(TypedInit *TI) {
319 if (TI->getType()->typeIsConvertibleTo(this))
324 Init *DagRecTy::convertValue(UnOpInit *BO) {
325 if (BO->getOpcode() == UnOpInit::CAST) {
326 Init *L = BO->getOperand()->convertInitializerTo(this);
327 if (!L) return nullptr;
328 if (L != BO->getOperand())
329 return UnOpInit::get(UnOpInit::CAST, L, new DagRecTy);
335 Init *DagRecTy::convertValue(BinOpInit *BO) {
336 if (BO->getOpcode() == BinOpInit::CONCAT) {
337 Init *L = BO->getLHS()->convertInitializerTo(this);
338 Init *R = BO->getRHS()->convertInitializerTo(this);
339 if (!L || !R) return nullptr;
340 if (L != BO->getLHS() || R != BO->getRHS())
341 return BinOpInit::get(BinOpInit::CONCAT, L, R, new DagRecTy);
347 RecordRecTy *RecordRecTy::get(Record *R) {
348 return dyn_cast<RecordRecTy>(R->getDefInit()->getType());
351 std::string RecordRecTy::getAsString() const {
352 return Rec->getName();
355 Init *RecordRecTy::convertValue(DefInit *DI) {
356 // Ensure that DI is a subclass of Rec.
357 if (!DI->getDef()->isSubClassOf(Rec))
362 Init *RecordRecTy::convertValue(TypedInit *TI) {
363 // Ensure that TI is compatible with Rec.
364 if (RecordRecTy *RRT = dyn_cast<RecordRecTy>(TI->getType()))
365 if (RRT->getRecord()->isSubClassOf(getRecord()) ||
366 RRT->getRecord() == getRecord())
371 bool RecordRecTy::baseClassOf(const RecTy *RHS) const{
372 const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
376 if (Rec == RTy->getRecord() || RTy->getRecord()->isSubClassOf(Rec))
379 const std::vector<Record*> &SC = Rec->getSuperClasses();
380 for (unsigned i = 0, e = SC.size(); i != e; ++i)
381 if (RTy->getRecord()->isSubClassOf(SC[i]))
387 /// resolveTypes - Find a common type that T1 and T2 convert to.
388 /// Return 0 if no such type exists.
390 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
391 if (T1->typeIsConvertibleTo(T2))
393 if (T2->typeIsConvertibleTo(T1))
396 // If one is a Record type, check superclasses
397 if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
398 // See if T2 inherits from a type T1 also inherits from
399 const std::vector<Record *> &T1SuperClasses =
400 RecTy1->getRecord()->getSuperClasses();
401 for(std::vector<Record *>::const_iterator i = T1SuperClasses.begin(),
402 iend = T1SuperClasses.end();
405 RecordRecTy *SuperRecTy1 = RecordRecTy::get(*i);
406 RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
408 if (NewType1 != SuperRecTy1) {
415 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) {
416 // See if T1 inherits from a type T2 also inherits from
417 const std::vector<Record *> &T2SuperClasses =
418 RecTy2->getRecord()->getSuperClasses();
419 for (std::vector<Record *>::const_iterator i = T2SuperClasses.begin(),
420 iend = T2SuperClasses.end();
423 RecordRecTy *SuperRecTy2 = RecordRecTy::get(*i);
424 RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
426 if (NewType2 != SuperRecTy2) {
437 //===----------------------------------------------------------------------===//
438 // Initializer implementations
439 //===----------------------------------------------------------------------===//
441 void Init::anchor() { }
442 void Init::dump() const { return print(errs()); }
444 void UnsetInit::anchor() { }
446 UnsetInit *UnsetInit::get() {
447 static UnsetInit TheInit;
451 void BitInit::anchor() { }
453 BitInit *BitInit::get(bool V) {
454 static BitInit True(true);
455 static BitInit False(false);
457 return V ? &True : &False;
461 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
462 ID.AddInteger(Range.size());
464 for (ArrayRef<Init *>::iterator i = Range.begin(),
471 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
472 typedef FoldingSet<BitsInit> Pool;
476 ProfileBitsInit(ID, Range);
479 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
482 BitsInit *I = new BitsInit(Range);
483 ThePool.InsertNode(I, IP);
488 void BitsInit::Profile(FoldingSetNodeID &ID) const {
489 ProfileBitsInit(ID, Bits);
493 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
494 SmallVector<Init *, 16> NewBits(Bits.size());
496 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
497 if (Bits[i] >= getNumBits())
499 NewBits[i] = getBit(Bits[i]);
501 return BitsInit::get(NewBits);
504 std::string BitsInit::getAsString() const {
505 std::string Result = "{ ";
506 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
507 if (i) Result += ", ";
508 if (Init *Bit = getBit(e-i-1))
509 Result += Bit->getAsString();
513 return Result + " }";
516 // Fix bit initializer to preserve the behavior that bit reference from a unset
517 // bits initializer will resolve into VarBitInit to keep the field name and bit
518 // number used in targets with fixed insn length.
519 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
520 if (RV || After != UnsetInit::get())
525 // resolveReferences - If there are any field references that refer to fields
526 // that have been filled in, we can propagate the values now.
528 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
529 bool Changed = false;
530 SmallVector<Init *, 16> NewBits(getNumBits());
532 Init *CachedInit = nullptr;
533 Init *CachedBitVar = nullptr;
534 bool CachedBitVarChanged = false;
536 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
537 Init *CurBit = Bits[i];
538 Init *CurBitVar = CurBit->getBitVar();
542 if (CurBitVar == CachedBitVar) {
543 if (CachedBitVarChanged) {
544 Init *Bit = CachedInit->getBit(CurBit->getBitNum());
545 NewBits[i] = fixBitInit(RV, CurBit, Bit);
549 CachedBitVar = CurBitVar;
550 CachedBitVarChanged = false;
555 CurBitVar = CurBitVar->resolveReferences(R, RV);
556 CachedBitVarChanged |= B != CurBitVar;
557 Changed |= B != CurBitVar;
558 } while (B != CurBitVar);
559 CachedInit = CurBitVar;
561 if (CachedBitVarChanged) {
562 Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
563 NewBits[i] = fixBitInit(RV, CurBit, Bit);
568 return BitsInit::get(NewBits);
570 return const_cast<BitsInit *>(this);
575 class Pool : public T {
581 for (typename T::iterator I = this->begin(), E = this->end(); I != E; ++I) {
582 typename T::value_type &Item = *I;
588 IntInit *IntInit::get(int64_t V) {
589 static Pool<DenseMap<int64_t, IntInit *> > ThePool;
591 IntInit *&I = ThePool[V];
592 if (!I) I = new IntInit(V);
596 std::string IntInit::getAsString() const {
597 return itostr(Value);
601 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
602 SmallVector<Init *, 16> NewBits(Bits.size());
604 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
608 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
610 return BitsInit::get(NewBits);
613 void StringInit::anchor() { }
615 StringInit *StringInit::get(StringRef V) {
616 static Pool<StringMap<StringInit *> > ThePool;
618 StringInit *&I = ThePool[V];
619 if (!I) I = new StringInit(V);
623 static void ProfileListInit(FoldingSetNodeID &ID,
624 ArrayRef<Init *> Range,
626 ID.AddInteger(Range.size());
627 ID.AddPointer(EltTy);
629 for (ArrayRef<Init *>::iterator i = Range.begin(),
636 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
637 typedef FoldingSet<ListInit> Pool;
639 static std::vector<std::unique_ptr<ListInit>> TheActualPool;
642 ProfileListInit(ID, Range, EltTy);
645 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
648 ListInit *I = new ListInit(Range, EltTy);
649 ThePool.InsertNode(I, IP);
650 TheActualPool.push_back(std::unique_ptr<ListInit>(I));
654 void ListInit::Profile(FoldingSetNodeID &ID) const {
655 ListRecTy *ListType = dyn_cast<ListRecTy>(getType());
656 assert(ListType && "Bad type for ListInit!");
657 RecTy *EltTy = ListType->getElementType();
659 ProfileListInit(ID, Values, EltTy);
663 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
664 std::vector<Init*> Vals;
665 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
666 if (Elements[i] >= getSize())
668 Vals.push_back(getElement(Elements[i]));
670 return ListInit::get(Vals, getType());
673 Record *ListInit::getElementAsRecord(unsigned i) const {
674 assert(i < Values.size() && "List element index out of range!");
675 DefInit *DI = dyn_cast<DefInit>(Values[i]);
677 PrintFatalError("Expected record in list!");
681 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
682 std::vector<Init*> Resolved;
683 Resolved.reserve(getSize());
684 bool Changed = false;
686 for (unsigned i = 0, e = getSize(); i != e; ++i) {
688 Init *CurElt = getElement(i);
692 CurElt = CurElt->resolveReferences(R, RV);
693 Changed |= E != CurElt;
694 } while (E != CurElt);
695 Resolved.push_back(E);
699 return ListInit::get(Resolved, getType());
700 return const_cast<ListInit *>(this);
703 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
704 unsigned Elt) const {
705 if (Elt >= getSize())
706 return nullptr; // Out of range reference.
707 Init *E = getElement(Elt);
708 // If the element is set to some value, or if we are resolving a reference
709 // to a specific variable and that variable is explicitly unset, then
710 // replace the VarListElementInit with it.
711 if (IRV || !isa<UnsetInit>(E))
716 std::string ListInit::getAsString() const {
717 std::string Result = "[";
718 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
719 if (i) Result += ", ";
720 Result += Values[i]->getAsString();
725 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
726 unsigned Elt) const {
727 Init *Resolved = resolveReferences(R, IRV);
728 OpInit *OResolved = dyn_cast<OpInit>(Resolved);
730 Resolved = OResolved->Fold(&R, nullptr);
733 if (Resolved != this) {
734 TypedInit *Typed = dyn_cast<TypedInit>(Resolved);
735 assert(Typed && "Expected typed init for list reference");
737 Init *New = Typed->resolveListElementReference(R, IRV, Elt);
740 return VarListElementInit::get(Typed, Elt);
747 Init *OpInit::getBit(unsigned Bit) const {
748 if (getType() == BitRecTy::get())
749 return const_cast<OpInit*>(this);
750 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
753 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
754 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
755 static Pool<DenseMap<Key, UnOpInit *> > ThePool;
757 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
759 UnOpInit *&I = ThePool[TheKey];
760 if (!I) I = new UnOpInit(opc, lhs, Type);
764 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
765 switch (getOpcode()) {
767 if (getType()->getAsString() == "string") {
768 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
771 if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
772 return StringInit::get(LHSd->getDef()->getName());
774 if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
775 return StringInit::get(LHSi->getAsString());
777 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
778 std::string Name = LHSs->getValue();
780 // From TGParser::ParseIDValue
782 if (const RecordVal *RV = CurRec->getValue(Name)) {
783 if (RV->getType() != getType())
784 PrintFatalError("type mismatch in cast");
785 return VarInit::get(Name, RV->getType());
788 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
791 if (CurRec->isTemplateArg(TemplateArgName)) {
792 const RecordVal *RV = CurRec->getValue(TemplateArgName);
793 assert(RV && "Template arg doesn't exist??");
795 if (RV->getType() != getType())
796 PrintFatalError("type mismatch in cast");
798 return VarInit::get(TemplateArgName, RV->getType());
803 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
805 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
806 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
807 assert(RV && "Template arg doesn't exist??");
809 if (RV->getType() != getType())
810 PrintFatalError("type mismatch in cast");
812 return VarInit::get(MCName, RV->getType());
816 if (Record *D = (CurRec->getRecords()).getDef(Name))
817 return DefInit::get(D);
819 PrintFatalError(CurRec->getLoc(),
820 "Undefined reference:'" + Name + "'\n");
826 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
827 assert(LHSl->getSize() != 0 && "Empty list in car");
828 return LHSl->getElement(0);
833 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
834 assert(LHSl->getSize() != 0 && "Empty list in cdr");
835 // Note the +1. We can't just pass the result of getValues()
837 ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
838 ArrayRef<Init *>::iterator end = LHSl->getValues().end();
840 ListInit::get(ArrayRef<Init *>(begin, end - begin),
847 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
848 if (LHSl->getSize() == 0) {
849 return IntInit::get(1);
851 return IntInit::get(0);
854 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
855 if (LHSs->getValue().empty()) {
856 return IntInit::get(1);
858 return IntInit::get(0);
865 return const_cast<UnOpInit *>(this);
868 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
869 Init *lhs = LHS->resolveReferences(R, RV);
872 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, nullptr);
873 return Fold(&R, nullptr);
876 std::string UnOpInit::getAsString() const {
879 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
880 case HEAD: Result = "!head"; break;
881 case TAIL: Result = "!tail"; break;
882 case EMPTY: Result = "!empty"; break;
884 return Result + "(" + LHS->getAsString() + ")";
887 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
888 Init *rhs, RecTy *Type) {
890 std::pair<std::pair<unsigned, Init *>, Init *>,
894 static Pool<DenseMap<Key, BinOpInit *> > ThePool;
896 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
899 BinOpInit *&I = ThePool[TheKey];
900 if (!I) I = new BinOpInit(opc, lhs, rhs, Type);
904 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
905 switch (getOpcode()) {
907 DagInit *LHSs = dyn_cast<DagInit>(LHS);
908 DagInit *RHSs = dyn_cast<DagInit>(RHS);
910 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
911 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
912 if (!LOp || !ROp || LOp->getDef() != ROp->getDef())
913 PrintFatalError("Concated Dag operators do not match!");
914 std::vector<Init*> Args;
915 std::vector<std::string> ArgNames;
916 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
917 Args.push_back(LHSs->getArg(i));
918 ArgNames.push_back(LHSs->getArgName(i));
920 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
921 Args.push_back(RHSs->getArg(i));
922 ArgNames.push_back(RHSs->getArgName(i));
924 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
929 ListInit *LHSs = dyn_cast<ListInit>(LHS);
930 ListInit *RHSs = dyn_cast<ListInit>(RHS);
932 std::vector<Init *> Args;
933 Args.insert(Args.end(), LHSs->begin(), LHSs->end());
934 Args.insert(Args.end(), RHSs->begin(), RHSs->end());
935 return ListInit::get(
936 Args, static_cast<ListRecTy *>(LHSs->getType())->getElementType());
941 StringInit *LHSs = dyn_cast<StringInit>(LHS);
942 StringInit *RHSs = dyn_cast<StringInit>(RHS);
944 return StringInit::get(LHSs->getValue() + RHSs->getValue());
948 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
949 // to string objects.
951 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
953 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
956 return IntInit::get(L->getValue() == R->getValue());
958 StringInit *LHSs = dyn_cast<StringInit>(LHS);
959 StringInit *RHSs = dyn_cast<StringInit>(RHS);
961 // Make sure we've resolved
963 return IntInit::get(LHSs->getValue() == RHSs->getValue());
973 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
975 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
977 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
979 switch (getOpcode()) {
980 default: llvm_unreachable("Bad opcode!");
981 case ADD: Result = LHSv + RHSv; break;
982 case AND: Result = LHSv & RHSv; break;
983 case SHL: Result = LHSv << RHSv; break;
984 case SRA: Result = LHSv >> RHSv; break;
985 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
987 return IntInit::get(Result);
992 return const_cast<BinOpInit *>(this);
995 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
996 Init *lhs = LHS->resolveReferences(R, RV);
997 Init *rhs = RHS->resolveReferences(R, RV);
999 if (LHS != lhs || RHS != rhs)
1000 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R,nullptr);
1001 return Fold(&R, nullptr);
1004 std::string BinOpInit::getAsString() const {
1007 case CONCAT: Result = "!con"; break;
1008 case ADD: Result = "!add"; break;
1009 case AND: Result = "!and"; break;
1010 case SHL: Result = "!shl"; break;
1011 case SRA: Result = "!sra"; break;
1012 case SRL: Result = "!srl"; break;
1013 case EQ: Result = "!eq"; break;
1014 case LISTCONCAT: Result = "!listconcat"; break;
1015 case STRCONCAT: Result = "!strconcat"; break;
1017 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
1020 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs,
1021 Init *mhs, Init *rhs,
1025 std::pair<std::pair<unsigned, RecTy *>, Init *>,
1031 typedef DenseMap<Key, TernOpInit *> Pool;
1032 static Pool ThePool;
1034 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
1040 TernOpInit *&I = ThePool[TheKey];
1041 if (!I) I = new TernOpInit(opc, lhs, mhs, rhs, Type);
1045 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1046 Record *CurRec, MultiClass *CurMultiClass);
1048 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
1049 RecTy *Type, Record *CurRec,
1050 MultiClass *CurMultiClass) {
1051 std::vector<Init *> NewOperands;
1053 TypedInit *TArg = dyn_cast<TypedInit>(Arg);
1055 // If this is a dag, recurse
1056 if (TArg && TArg->getType()->getAsString() == "dag") {
1057 Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
1058 CurRec, CurMultiClass);
1062 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
1063 OpInit *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i));
1066 Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1067 Type, CurRec, CurMultiClass);
1069 NewOperands.push_back(Result);
1071 NewOperands.push_back(Arg);
1073 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1074 NewOperands.push_back(Arg);
1076 NewOperands.push_back(RHSo->getOperand(i));
1080 // Now run the operator and use its result as the new leaf
1081 const OpInit *NewOp = RHSo->clone(NewOperands);
1082 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
1083 return (NewVal != NewOp) ? NewVal : nullptr;
1086 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1087 Record *CurRec, MultiClass *CurMultiClass) {
1088 DagInit *MHSd = dyn_cast<DagInit>(MHS);
1089 ListInit *MHSl = dyn_cast<ListInit>(MHS);
1091 OpInit *RHSo = dyn_cast<OpInit>(RHS);
1094 PrintFatalError(CurRec->getLoc(), "!foreach requires an operator\n");
1097 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1100 PrintFatalError(CurRec->getLoc(), "!foreach requires typed variable\n");
1102 if ((MHSd && isa<DagRecTy>(Type)) || (MHSl && isa<ListRecTy>(Type))) {
1104 Init *Val = MHSd->getOperator();
1105 Init *Result = EvaluateOperation(RHSo, LHS, Val,
1106 Type, CurRec, CurMultiClass);
1111 std::vector<std::pair<Init *, std::string> > args;
1112 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1114 std::string ArgName;
1115 Arg = MHSd->getArg(i);
1116 ArgName = MHSd->getArgName(i);
1119 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1120 CurRec, CurMultiClass);
1125 // TODO: Process arg names
1126 args.push_back(std::make_pair(Arg, ArgName));
1129 return DagInit::get(Val, "", args);
1132 std::vector<Init *> NewOperands;
1133 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1135 for (std::vector<Init *>::iterator li = NewList.begin(),
1136 liend = NewList.end();
1140 NewOperands.clear();
1141 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1142 // First, replace the foreach variable with the list item
1143 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1144 NewOperands.push_back(Item);
1146 NewOperands.push_back(RHSo->getOperand(i));
1150 // Now run the operator and use its result as the new list item
1151 const OpInit *NewOp = RHSo->clone(NewOperands);
1152 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1153 if (NewItem != NewOp)
1156 return ListInit::get(NewList, MHSl->getType());
1162 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1163 switch (getOpcode()) {
1165 DefInit *LHSd = dyn_cast<DefInit>(LHS);
1166 VarInit *LHSv = dyn_cast<VarInit>(LHS);
1167 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1169 DefInit *MHSd = dyn_cast<DefInit>(MHS);
1170 VarInit *MHSv = dyn_cast<VarInit>(MHS);
1171 StringInit *MHSs = dyn_cast<StringInit>(MHS);
1173 DefInit *RHSd = dyn_cast<DefInit>(RHS);
1174 VarInit *RHSv = dyn_cast<VarInit>(RHS);
1175 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1177 if ((LHSd && MHSd && RHSd)
1178 || (LHSv && MHSv && RHSv)
1179 || (LHSs && MHSs && RHSs)) {
1181 Record *Val = RHSd->getDef();
1182 if (LHSd->getAsString() == RHSd->getAsString()) {
1183 Val = MHSd->getDef();
1185 return DefInit::get(Val);
1188 std::string Val = RHSv->getName();
1189 if (LHSv->getAsString() == RHSv->getAsString()) {
1190 Val = MHSv->getName();
1192 return VarInit::get(Val, getType());
1195 std::string Val = RHSs->getValue();
1197 std::string::size_type found;
1198 std::string::size_type idx = 0;
1200 found = Val.find(LHSs->getValue(), idx);
1201 if (found != std::string::npos) {
1202 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1204 idx = found + MHSs->getValue().size();
1205 } while (found != std::string::npos);
1207 return StringInit::get(Val);
1214 Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1215 CurRec, CurMultiClass);
1223 IntInit *LHSi = dyn_cast<IntInit>(LHS);
1224 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1225 LHSi = dyn_cast<IntInit>(I);
1227 if (LHSi->getValue()) {
1237 return const_cast<TernOpInit *>(this);
1240 Init *TernOpInit::resolveReferences(Record &R,
1241 const RecordVal *RV) const {
1242 Init *lhs = LHS->resolveReferences(R, RV);
1244 if (Opc == IF && lhs != LHS) {
1245 IntInit *Value = dyn_cast<IntInit>(lhs);
1246 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1247 Value = dyn_cast<IntInit>(I);
1250 if (Value->getValue()) {
1251 Init *mhs = MHS->resolveReferences(R, RV);
1252 return (TernOpInit::get(getOpcode(), lhs, mhs,
1253 RHS, getType()))->Fold(&R, nullptr);
1255 Init *rhs = RHS->resolveReferences(R, RV);
1256 return (TernOpInit::get(getOpcode(), lhs, MHS,
1257 rhs, getType()))->Fold(&R, nullptr);
1262 Init *mhs = MHS->resolveReferences(R, RV);
1263 Init *rhs = RHS->resolveReferences(R, RV);
1265 if (LHS != lhs || MHS != mhs || RHS != rhs)
1266 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1267 getType()))->Fold(&R, nullptr);
1268 return Fold(&R, nullptr);
1271 std::string TernOpInit::getAsString() const {
1274 case SUBST: Result = "!subst"; break;
1275 case FOREACH: Result = "!foreach"; break;
1276 case IF: Result = "!if"; break;
1278 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
1279 + RHS->getAsString() + ")";
1282 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1283 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
1284 if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
1285 return Field->getType();
1290 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1291 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1292 if (!T) return nullptr; // Cannot subscript a non-bits variable.
1293 unsigned NumBits = T->getNumBits();
1295 SmallVector<Init *, 16> NewBits(Bits.size());
1296 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1297 if (Bits[i] >= NumBits)
1300 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1302 return BitsInit::get(NewBits);
1306 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1307 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1308 if (!T) return nullptr; // Cannot subscript a non-list variable.
1310 if (Elements.size() == 1)
1311 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1313 std::vector<Init*> ListInits;
1314 ListInits.reserve(Elements.size());
1315 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1316 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1318 return ListInit::get(ListInits, T);
1322 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1323 Init *Value = StringInit::get(VN);
1324 return VarInit::get(Value, T);
1327 VarInit *VarInit::get(Init *VN, RecTy *T) {
1328 typedef std::pair<RecTy *, Init *> Key;
1329 static Pool<DenseMap<Key, VarInit *> > ThePool;
1331 Key TheKey(std::make_pair(T, VN));
1333 VarInit *&I = ThePool[TheKey];
1334 if (!I) I = new VarInit(VN, T);
1338 const std::string &VarInit::getName() const {
1339 StringInit *NameString = dyn_cast<StringInit>(getNameInit());
1340 assert(NameString && "VarInit name is not a string!");
1341 return NameString->getValue();
1344 Init *VarInit::getBit(unsigned Bit) const {
1345 if (getType() == BitRecTy::get())
1346 return const_cast<VarInit*>(this);
1347 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1350 Init *VarInit::resolveListElementReference(Record &R,
1351 const RecordVal *IRV,
1352 unsigned Elt) const {
1353 if (R.isTemplateArg(getNameInit())) return nullptr;
1354 if (IRV && IRV->getNameInit() != getNameInit()) return nullptr;
1356 RecordVal *RV = R.getValue(getNameInit());
1357 assert(RV && "Reference to a non-existent variable?");
1358 ListInit *LI = dyn_cast<ListInit>(RV->getValue());
1360 TypedInit *VI = dyn_cast<TypedInit>(RV->getValue());
1361 assert(VI && "Invalid list element!");
1362 return VarListElementInit::get(VI, Elt);
1365 if (Elt >= LI->getSize())
1366 return nullptr; // Out of range reference.
1367 Init *E = LI->getElement(Elt);
1368 // If the element is set to some value, or if we are resolving a reference
1369 // to a specific variable and that variable is explicitly unset, then
1370 // replace the VarListElementInit with it.
1371 if (IRV || !isa<UnsetInit>(E))
1377 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1378 if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
1379 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1380 return RV->getType();
1384 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1385 const std::string &FieldName) const {
1386 if (isa<RecordRecTy>(getType()))
1387 if (const RecordVal *Val = R.getValue(VarName)) {
1388 if (RV != Val && (RV || isa<UnsetInit>(Val->getValue())))
1390 Init *TheInit = Val->getValue();
1391 assert(TheInit != this && "Infinite loop detected!");
1392 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1400 /// resolveReferences - This method is used by classes that refer to other
1401 /// variables which may not be defined at the time the expression is formed.
1402 /// If a value is set for the variable later, this method will be called on
1403 /// users of the value to allow the value to propagate out.
1405 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1406 if (RecordVal *Val = R.getValue(VarName))
1407 if (RV == Val || (!RV && !isa<UnsetInit>(Val->getValue())))
1408 return Val->getValue();
1409 return const_cast<VarInit *>(this);
1412 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1413 typedef std::pair<TypedInit *, unsigned> Key;
1414 typedef DenseMap<Key, VarBitInit *> Pool;
1416 static Pool ThePool;
1418 Key TheKey(std::make_pair(T, B));
1420 VarBitInit *&I = ThePool[TheKey];
1421 if (!I) I = new VarBitInit(T, B);
1425 std::string VarBitInit::getAsString() const {
1426 return TI->getAsString() + "{" + utostr(Bit) + "}";
1429 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1430 Init *I = TI->resolveReferences(R, RV);
1432 return I->getBit(getBitNum());
1434 return const_cast<VarBitInit*>(this);
1437 VarListElementInit *VarListElementInit::get(TypedInit *T,
1439 typedef std::pair<TypedInit *, unsigned> Key;
1440 typedef DenseMap<Key, VarListElementInit *> Pool;
1442 static Pool ThePool;
1444 Key TheKey(std::make_pair(T, E));
1446 VarListElementInit *&I = ThePool[TheKey];
1447 if (!I) I = new VarListElementInit(T, E);
1451 std::string VarListElementInit::getAsString() const {
1452 return TI->getAsString() + "[" + utostr(Element) + "]";
1456 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1457 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1460 return const_cast<VarListElementInit *>(this);
1463 Init *VarListElementInit::getBit(unsigned Bit) const {
1464 if (getType() == BitRecTy::get())
1465 return const_cast<VarListElementInit*>(this);
1466 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1469 Init *VarListElementInit:: resolveListElementReference(Record &R,
1470 const RecordVal *RV,
1471 unsigned Elt) const {
1472 Init *Result = TI->resolveListElementReference(R, RV, Element);
1475 if (TypedInit *TInit = dyn_cast<TypedInit>(Result)) {
1476 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1477 if (Result2) return Result2;
1478 return new VarListElementInit(TInit, Elt);
1486 DefInit *DefInit::get(Record *R) {
1487 return R->getDefInit();
1490 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1491 if (const RecordVal *RV = Def->getValue(FieldName))
1492 return RV->getType();
1496 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1497 const std::string &FieldName) const {
1498 return Def->getValue(FieldName)->getValue();
1502 std::string DefInit::getAsString() const {
1503 return Def->getName();
1506 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1507 typedef std::pair<Init *, TableGenStringKey> Key;
1508 typedef DenseMap<Key, FieldInit *> Pool;
1509 static Pool ThePool;
1511 Key TheKey(std::make_pair(R, FN));
1513 FieldInit *&I = ThePool[TheKey];
1514 if (!I) I = new FieldInit(R, FN);
1518 Init *FieldInit::getBit(unsigned Bit) const {
1519 if (getType() == BitRecTy::get())
1520 return const_cast<FieldInit*>(this);
1521 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1524 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1525 unsigned Elt) const {
1526 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1527 if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
1528 if (Elt >= LI->getSize()) return nullptr;
1529 Init *E = LI->getElement(Elt);
1531 // If the element is set to some value, or if we are resolving a
1532 // reference to a specific variable and that variable is explicitly
1533 // unset, then replace the VarListElementInit with it.
1534 if (RV || !isa<UnsetInit>(E))
1540 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1541 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1543 Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1545 Init *BVR = BitsVal->resolveReferences(R, RV);
1546 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1549 if (NewRec != Rec) {
1550 return FieldInit::get(NewRec, FieldName);
1552 return const_cast<FieldInit *>(this);
1555 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, const std::string &VN,
1556 ArrayRef<Init *> ArgRange,
1557 ArrayRef<std::string> NameRange) {
1561 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1562 ArrayRef<std::string>::iterator Name = NameRange.begin();
1563 while (Arg != ArgRange.end()) {
1564 assert(Name != NameRange.end() && "Arg name underflow!");
1565 ID.AddPointer(*Arg++);
1566 ID.AddString(*Name++);
1568 assert(Name == NameRange.end() && "Arg name overflow!");
1572 DagInit::get(Init *V, const std::string &VN,
1573 ArrayRef<Init *> ArgRange,
1574 ArrayRef<std::string> NameRange) {
1575 typedef FoldingSet<DagInit> Pool;
1576 static Pool ThePool;
1578 FoldingSetNodeID ID;
1579 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1582 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1585 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1586 ThePool.InsertNode(I, IP);
1592 DagInit::get(Init *V, const std::string &VN,
1593 const std::vector<std::pair<Init*, std::string> > &args) {
1594 typedef std::pair<Init*, std::string> PairType;
1596 std::vector<Init *> Args;
1597 std::vector<std::string> Names;
1599 for (std::vector<PairType>::const_iterator i = args.begin(),
1603 Args.push_back(i->first);
1604 Names.push_back(i->second);
1607 return DagInit::get(V, VN, Args, Names);
1610 void DagInit::Profile(FoldingSetNodeID &ID) const {
1611 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1614 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1615 std::vector<Init*> NewArgs;
1616 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1617 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1619 Init *Op = Val->resolveReferences(R, RV);
1621 if (Args != NewArgs || Op != Val)
1622 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1624 return const_cast<DagInit *>(this);
1628 std::string DagInit::getAsString() const {
1629 std::string Result = "(" + Val->getAsString();
1630 if (!ValName.empty())
1631 Result += ":" + ValName;
1633 Result += " " + Args[0]->getAsString();
1634 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1635 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1636 Result += ", " + Args[i]->getAsString();
1637 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1640 return Result + ")";
1644 //===----------------------------------------------------------------------===//
1645 // Other implementations
1646 //===----------------------------------------------------------------------===//
1648 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1649 : Name(N), Ty(T), Prefix(P) {
1650 Value = Ty->convertValue(UnsetInit::get());
1651 assert(Value && "Cannot create unset value for current type!");
1654 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1655 : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1656 Value = Ty->convertValue(UnsetInit::get());
1657 assert(Value && "Cannot create unset value for current type!");
1660 const std::string &RecordVal::getName() const {
1661 StringInit *NameString = dyn_cast<StringInit>(Name);
1662 assert(NameString && "RecordVal name is not a string!");
1663 return NameString->getValue();
1666 void RecordVal::dump() const { errs() << *this; }
1668 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1669 if (getPrefix()) OS << "field ";
1670 OS << *getType() << " " << getNameInitAsString();
1673 OS << " = " << *getValue();
1675 if (PrintSem) OS << ";\n";
1678 unsigned Record::LastID = 0;
1680 void Record::init() {
1683 // Every record potentially has a def at the top. This value is
1684 // replaced with the top-level def name at instantiation time.
1685 RecordVal DN("NAME", StringRecTy::get(), 0);
1689 void Record::checkName() {
1690 // Ensure the record name has string type.
1691 const TypedInit *TypedName = dyn_cast<const TypedInit>(Name);
1692 assert(TypedName && "Record name is not typed!");
1693 RecTy *Type = TypedName->getType();
1694 if (!isa<StringRecTy>(Type))
1695 PrintFatalError(getLoc(), "Record name is not a string!");
1698 DefInit *Record::getDefInit() {
1700 TheInit = new DefInit(this, new RecordRecTy(this));
1704 const std::string &Record::getName() const {
1705 const StringInit *NameString = dyn_cast<StringInit>(Name);
1706 assert(NameString && "Record name is not a string!");
1707 return NameString->getValue();
1710 void Record::setName(Init *NewName) {
1713 // DO NOT resolve record values to the name at this point because
1714 // there might be default values for arguments of this def. Those
1715 // arguments might not have been resolved yet so we don't want to
1716 // prematurely assume values for those arguments were not passed to
1719 // Nonetheless, it may be that some of this Record's values
1720 // reference the record name. Indeed, the reason for having the
1721 // record name be an Init is to provide this flexibility. The extra
1722 // resolve steps after completely instantiating defs takes care of
1723 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1726 void Record::setName(const std::string &Name) {
1727 setName(StringInit::get(Name));
1730 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1731 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1733 void Record::resolveReferencesTo(const RecordVal *RV) {
1734 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1735 if (RV == &Values[i]) // Skip resolve the same field as the given one
1737 if (Init *V = Values[i].getValue())
1738 if (Values[i].setValue(V->resolveReferences(*this, RV)))
1739 PrintFatalError(getLoc(), "Invalid value is found when setting '"
1740 + Values[i].getNameInitAsString()
1741 + "' after resolving references"
1742 + (RV ? " against '" + RV->getNameInitAsString()
1744 + RV->getValue()->getAsUnquotedString() + ")"
1748 Init *OldName = getNameInit();
1749 Init *NewName = Name->resolveReferences(*this, RV);
1750 if (NewName != OldName) {
1751 // Re-register with RecordKeeper.
1756 void Record::dump() const { errs() << *this; }
1758 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1759 OS << R.getNameInitAsString();
1761 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1762 if (!TArgs.empty()) {
1764 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1766 const RecordVal *RV = R.getValue(TArgs[i]);
1767 assert(RV && "Template argument record not found??");
1768 RV->print(OS, false);
1774 const std::vector<Record*> &SC = R.getSuperClasses();
1777 for (unsigned i = 0, e = SC.size(); i != e; ++i)
1778 OS << " " << SC[i]->getNameInitAsString();
1782 const std::vector<RecordVal> &Vals = R.getValues();
1783 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1784 if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1786 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1787 if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1793 /// getValueInit - Return the initializer for a value with the specified name,
1794 /// or abort if the field does not exist.
1796 Init *Record::getValueInit(StringRef FieldName) const {
1797 const RecordVal *R = getValue(FieldName);
1798 if (!R || !R->getValue())
1799 PrintFatalError(getLoc(), "Record `" + getName() +
1800 "' does not have a field named `" + FieldName + "'!\n");
1801 return R->getValue();
1805 /// getValueAsString - This method looks up the specified field and returns its
1806 /// value as a string, aborts if the field does not exist or if
1807 /// the value is not a string.
1809 std::string Record::getValueAsString(StringRef FieldName) const {
1810 const RecordVal *R = getValue(FieldName);
1811 if (!R || !R->getValue())
1812 PrintFatalError(getLoc(), "Record `" + getName() +
1813 "' does not have a field named `" + FieldName + "'!\n");
1815 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1816 return SI->getValue();
1817 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1818 FieldName + "' does not have a string initializer!");
1821 /// getValueAsBitsInit - This method looks up the specified field and returns
1822 /// its value as a BitsInit, aborts if the field does not exist or if
1823 /// the value is not the right type.
1825 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1826 const RecordVal *R = getValue(FieldName);
1827 if (!R || !R->getValue())
1828 PrintFatalError(getLoc(), "Record `" + getName() +
1829 "' does not have a field named `" + FieldName + "'!\n");
1831 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
1833 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1834 FieldName + "' does not have a BitsInit initializer!");
1837 /// getValueAsListInit - This method looks up the specified field and returns
1838 /// its value as a ListInit, aborting if the field does not exist or if
1839 /// the value is not the right type.
1841 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1842 const RecordVal *R = getValue(FieldName);
1843 if (!R || !R->getValue())
1844 PrintFatalError(getLoc(), "Record `" + getName() +
1845 "' does not have a field named `" + FieldName + "'!\n");
1847 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
1849 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1850 FieldName + "' does not have a list initializer!");
1853 /// getValueAsListOfDefs - This method looks up the specified field and returns
1854 /// its value as a vector of records, aborting if the field does not exist
1855 /// or if the value is not the right type.
1857 std::vector<Record*>
1858 Record::getValueAsListOfDefs(StringRef FieldName) const {
1859 ListInit *List = getValueAsListInit(FieldName);
1860 std::vector<Record*> Defs;
1861 for (unsigned i = 0; i < List->getSize(); i++) {
1862 if (DefInit *DI = dyn_cast<DefInit>(List->getElement(i))) {
1863 Defs.push_back(DI->getDef());
1865 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1866 FieldName + "' list is not entirely DefInit!");
1872 /// getValueAsInt - This method looks up the specified field and returns its
1873 /// value as an int64_t, aborting if the field does not exist or if the value
1874 /// is not the right type.
1876 int64_t Record::getValueAsInt(StringRef FieldName) const {
1877 const RecordVal *R = getValue(FieldName);
1878 if (!R || !R->getValue())
1879 PrintFatalError(getLoc(), "Record `" + getName() +
1880 "' does not have a field named `" + FieldName + "'!\n");
1882 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
1883 return II->getValue();
1884 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1885 FieldName + "' does not have an int initializer!");
1888 /// getValueAsListOfInts - This method looks up the specified field and returns
1889 /// its value as a vector of integers, aborting if the field does not exist or
1890 /// if the value is not the right type.
1892 std::vector<int64_t>
1893 Record::getValueAsListOfInts(StringRef FieldName) const {
1894 ListInit *List = getValueAsListInit(FieldName);
1895 std::vector<int64_t> Ints;
1896 for (unsigned i = 0; i < List->getSize(); i++) {
1897 if (IntInit *II = dyn_cast<IntInit>(List->getElement(i))) {
1898 Ints.push_back(II->getValue());
1900 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1901 FieldName + "' does not have a list of ints initializer!");
1907 /// getValueAsListOfStrings - This method looks up the specified field and
1908 /// returns its value as a vector of strings, aborting if the field does not
1909 /// exist or if the value is not the right type.
1911 std::vector<std::string>
1912 Record::getValueAsListOfStrings(StringRef FieldName) const {
1913 ListInit *List = getValueAsListInit(FieldName);
1914 std::vector<std::string> Strings;
1915 for (unsigned i = 0; i < List->getSize(); i++) {
1916 if (StringInit *II = dyn_cast<StringInit>(List->getElement(i))) {
1917 Strings.push_back(II->getValue());
1919 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1920 FieldName + "' does not have a list of strings initializer!");
1926 /// getValueAsDef - This method looks up the specified field and returns its
1927 /// value as a Record, aborting if the field does not exist or if the value
1928 /// is not the right type.
1930 Record *Record::getValueAsDef(StringRef FieldName) const {
1931 const RecordVal *R = getValue(FieldName);
1932 if (!R || !R->getValue())
1933 PrintFatalError(getLoc(), "Record `" + getName() +
1934 "' does not have a field named `" + FieldName + "'!\n");
1936 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
1937 return DI->getDef();
1938 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1939 FieldName + "' does not have a def initializer!");
1942 /// getValueAsBit - This method looks up the specified field and returns its
1943 /// value as a bit, aborting if the field does not exist or if the value is
1944 /// not the right type.
1946 bool Record::getValueAsBit(StringRef FieldName) const {
1947 const RecordVal *R = getValue(FieldName);
1948 if (!R || !R->getValue())
1949 PrintFatalError(getLoc(), "Record `" + getName() +
1950 "' does not have a field named `" + FieldName + "'!\n");
1952 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1953 return BI->getValue();
1954 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1955 FieldName + "' does not have a bit initializer!");
1958 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1959 const RecordVal *R = getValue(FieldName);
1960 if (!R || !R->getValue())
1961 PrintFatalError(getLoc(), "Record `" + getName() +
1962 "' does not have a field named `" + FieldName.str() + "'!\n");
1964 if (R->getValue() == UnsetInit::get()) {
1969 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1970 return BI->getValue();
1971 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1972 FieldName + "' does not have a bit initializer!");
1975 /// getValueAsDag - This method looks up the specified field and returns its
1976 /// value as an Dag, aborting if the field does not exist or if the value is
1977 /// not the right type.
1979 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1980 const RecordVal *R = getValue(FieldName);
1981 if (!R || !R->getValue())
1982 PrintFatalError(getLoc(), "Record `" + getName() +
1983 "' does not have a field named `" + FieldName + "'!\n");
1985 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
1987 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1988 FieldName + "' does not have a dag initializer!");
1992 void MultiClass::dump() const {
1993 errs() << "Record:\n";
1996 errs() << "Defs:\n";
1997 for (RecordVector::const_iterator r = DefPrototypes.begin(),
1998 rend = DefPrototypes.end();
2006 void RecordKeeper::dump() const { errs() << *this; }
2008 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
2009 OS << "------------- Classes -----------------\n";
2010 const auto &Classes = RK.getClasses();
2011 for (const auto &C : Classes)
2012 OS << "class " << *C.second;
2014 OS << "------------- Defs -----------------\n";
2015 const auto &Defs = RK.getDefs();
2016 for (const auto &D : Defs)
2017 OS << "def " << *D.second;
2022 /// getAllDerivedDefinitions - This method returns all concrete definitions
2023 /// that derive from the specified class name. If a class with the specified
2024 /// name does not exist, an error is printed and true is returned.
2025 std::vector<Record*>
2026 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
2027 Record *Class = getClass(ClassName);
2029 PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
2031 std::vector<Record*> Defs;
2032 for (const auto &D : getDefs())
2033 if (D.second->isSubClassOf(Class))
2034 Defs.push_back(D.second.get());
2039 /// QualifyName - Return an Init with a qualifier prefix referring
2040 /// to CurRec's name.
2041 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2042 Init *Name, const std::string &Scoper) {
2043 RecTy *Type = dyn_cast<TypedInit>(Name)->getType();
2045 BinOpInit *NewName =
2046 BinOpInit::get(BinOpInit::STRCONCAT,
2047 BinOpInit::get(BinOpInit::STRCONCAT,
2048 CurRec.getNameInit(),
2049 StringInit::get(Scoper),
2050 Type)->Fold(&CurRec, CurMultiClass),
2054 if (CurMultiClass && Scoper != "::") {
2056 BinOpInit::get(BinOpInit::STRCONCAT,
2057 BinOpInit::get(BinOpInit::STRCONCAT,
2058 CurMultiClass->Rec.getNameInit(),
2059 StringInit::get("::"),
2060 Type)->Fold(&CurRec, CurMultiClass),
2061 NewName->Fold(&CurRec, CurMultiClass),
2065 return NewName->Fold(&CurRec, CurMultiClass);
2068 /// QualifyName - Return an Init with a qualifier prefix referring
2069 /// to CurRec's name.
2070 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2071 const std::string &Name,
2072 const std::string &Scoper) {
2073 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);