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) || isa<BitsRecTy>(Ty) || isa<IntRecTy>(Ty))
118 return VI; // Accept variable if it is already of bit type!
122 bool BitRecTy::baseClassOf(const RecTy *RHS) const{
123 if(RecTy::baseClassOf(RHS) || getRecTyKind() == IntRecTyKind)
125 if(const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
126 return BitsTy->getNumBits() == 1;
130 BitsRecTy *BitsRecTy::get(unsigned Sz) {
131 static std::vector<BitsRecTy*> Shared;
132 if (Sz >= Shared.size())
133 Shared.resize(Sz + 1);
134 BitsRecTy *&Ty = Shared[Sz];
136 Ty = new BitsRecTy(Sz);
140 std::string BitsRecTy::getAsString() const {
141 return "bits<" + utostr(Size) + ">";
144 Init *BitsRecTy::convertValue(UnsetInit *UI) {
145 SmallVector<Init *, 16> NewBits(Size);
147 for (unsigned i = 0; i != Size; ++i)
148 NewBits[i] = UnsetInit::get();
150 return BitsInit::get(NewBits);
153 Init *BitsRecTy::convertValue(BitInit *UI) {
154 if (Size != 1) return nullptr; // Can only convert single bit.
155 return BitsInit::get(UI);
158 /// canFitInBitfield - Return true if the number of bits is large enough to hold
159 /// the integer value.
160 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
161 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
162 return (NumBits >= sizeof(Value) * 8) ||
163 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
166 /// convertValue from Int initializer to bits type: Split the integer up into the
167 /// appropriate bits.
169 Init *BitsRecTy::convertValue(IntInit *II) {
170 int64_t Value = II->getValue();
171 // Make sure this bitfield is large enough to hold the integer value.
172 if (!canFitInBitfield(Value, Size))
175 SmallVector<Init *, 16> NewBits(Size);
177 for (unsigned i = 0; i != Size; ++i)
178 NewBits[i] = BitInit::get(Value & (1LL << i));
180 return BitsInit::get(NewBits);
183 Init *BitsRecTy::convertValue(BitsInit *BI) {
184 // If the number of bits is right, return it. Otherwise we need to expand or
186 if (BI->getNumBits() == Size) return BI;
190 Init *BitsRecTy::convertValue(TypedInit *VI) {
191 if (Size == 1 && isa<BitRecTy>(VI->getType()))
192 return BitsInit::get(VI);
194 if (VI->getType()->typeIsConvertibleTo(this)) {
195 SmallVector<Init *, 16> NewBits(Size);
197 for (unsigned i = 0; i != Size; ++i)
198 NewBits[i] = VarBitInit::get(VI, i);
199 return BitsInit::get(NewBits);
205 bool BitsRecTy::baseClassOf(const RecTy *RHS) const{
206 if (RecTy::baseClassOf(RHS)) //argument and the receiver are the same type
207 return cast<BitsRecTy>(RHS)->Size == Size;
208 RecTyKind kind = RHS->getRecTyKind();
209 return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
212 Init *IntRecTy::convertValue(BitInit *BI) {
213 return IntInit::get(BI->getValue());
216 Init *IntRecTy::convertValue(BitsInit *BI) {
218 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
219 if (BitInit *Bit = dyn_cast<BitInit>(BI->getBit(i))) {
220 Result |= Bit->getValue() << i;
224 return IntInit::get(Result);
227 Init *IntRecTy::convertValue(TypedInit *TI) {
228 if (TI->getType()->typeIsConvertibleTo(this))
229 return TI; // Accept variable if already of the right type!
233 bool IntRecTy::baseClassOf(const RecTy *RHS) const{
234 RecTyKind kind = RHS->getRecTyKind();
235 return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
238 Init *StringRecTy::convertValue(UnOpInit *BO) {
239 if (BO->getOpcode() == UnOpInit::CAST) {
240 Init *L = BO->getOperand()->convertInitializerTo(this);
241 if (!L) return nullptr;
242 if (L != BO->getOperand())
243 return UnOpInit::get(UnOpInit::CAST, L, new StringRecTy);
247 return convertValue((TypedInit*)BO);
250 Init *StringRecTy::convertValue(BinOpInit *BO) {
251 if (BO->getOpcode() == BinOpInit::STRCONCAT) {
252 Init *L = BO->getLHS()->convertInitializerTo(this);
253 Init *R = BO->getRHS()->convertInitializerTo(this);
254 if (!L || !R) return nullptr;
255 if (L != BO->getLHS() || R != BO->getRHS())
256 return BinOpInit::get(BinOpInit::STRCONCAT, L, R, new StringRecTy);
260 return convertValue((TypedInit*)BO);
264 Init *StringRecTy::convertValue(TypedInit *TI) {
265 if (isa<StringRecTy>(TI->getType()))
266 return TI; // Accept variable if already of the right type!
270 std::string ListRecTy::getAsString() const {
271 return "list<" + Ty->getAsString() + ">";
274 Init *ListRecTy::convertValue(ListInit *LI) {
275 std::vector<Init*> Elements;
277 // Verify that all of the elements of the list are subclasses of the
278 // appropriate class!
279 for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
280 if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
281 Elements.push_back(CI);
285 if (!isa<ListRecTy>(LI->getType()))
288 return ListInit::get(Elements, this);
291 Init *ListRecTy::convertValue(TypedInit *TI) {
292 // Ensure that TI is compatible with our class.
293 if (ListRecTy *LRT = dyn_cast<ListRecTy>(TI->getType()))
294 if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
299 bool ListRecTy::baseClassOf(const RecTy *RHS) const{
300 if(const ListRecTy* ListTy = dyn_cast<ListRecTy>(RHS))
301 return ListTy->getElementType()->typeIsConvertibleTo(Ty);
305 Init *DagRecTy::convertValue(TypedInit *TI) {
306 if (TI->getType()->typeIsConvertibleTo(this))
311 Init *DagRecTy::convertValue(UnOpInit *BO) {
312 if (BO->getOpcode() == UnOpInit::CAST) {
313 Init *L = BO->getOperand()->convertInitializerTo(this);
314 if (!L) return nullptr;
315 if (L != BO->getOperand())
316 return UnOpInit::get(UnOpInit::CAST, L, new DagRecTy);
322 Init *DagRecTy::convertValue(BinOpInit *BO) {
323 if (BO->getOpcode() == BinOpInit::CONCAT) {
324 Init *L = BO->getLHS()->convertInitializerTo(this);
325 Init *R = BO->getRHS()->convertInitializerTo(this);
326 if (!L || !R) return nullptr;
327 if (L != BO->getLHS() || R != BO->getRHS())
328 return BinOpInit::get(BinOpInit::CONCAT, L, R, new DagRecTy);
334 RecordRecTy *RecordRecTy::get(Record *R) {
335 return dyn_cast<RecordRecTy>(R->getDefInit()->getType());
338 std::string RecordRecTy::getAsString() const {
339 return Rec->getName();
342 Init *RecordRecTy::convertValue(DefInit *DI) {
343 // Ensure that DI is a subclass of Rec.
344 if (!DI->getDef()->isSubClassOf(Rec))
349 Init *RecordRecTy::convertValue(TypedInit *TI) {
350 // Ensure that TI is compatible with Rec.
351 if (RecordRecTy *RRT = dyn_cast<RecordRecTy>(TI->getType()))
352 if (RRT->getRecord()->isSubClassOf(getRecord()) ||
353 RRT->getRecord() == getRecord())
358 bool RecordRecTy::baseClassOf(const RecTy *RHS) const{
359 const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
363 if (Rec == RTy->getRecord() || RTy->getRecord()->isSubClassOf(Rec))
366 const std::vector<Record*> &SC = Rec->getSuperClasses();
367 for (unsigned i = 0, e = SC.size(); i != e; ++i)
368 if (RTy->getRecord()->isSubClassOf(SC[i]))
374 /// resolveTypes - Find a common type that T1 and T2 convert to.
375 /// Return 0 if no such type exists.
377 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
378 if (T1->typeIsConvertibleTo(T2))
380 if (T2->typeIsConvertibleTo(T1))
383 // If one is a Record type, check superclasses
384 if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
385 // See if T2 inherits from a type T1 also inherits from
386 const std::vector<Record *> &T1SuperClasses =
387 RecTy1->getRecord()->getSuperClasses();
388 for(std::vector<Record *>::const_iterator i = T1SuperClasses.begin(),
389 iend = T1SuperClasses.end();
392 RecordRecTy *SuperRecTy1 = RecordRecTy::get(*i);
393 RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
395 if (NewType1 != SuperRecTy1) {
402 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) {
403 // See if T1 inherits from a type T2 also inherits from
404 const std::vector<Record *> &T2SuperClasses =
405 RecTy2->getRecord()->getSuperClasses();
406 for (std::vector<Record *>::const_iterator i = T2SuperClasses.begin(),
407 iend = T2SuperClasses.end();
410 RecordRecTy *SuperRecTy2 = RecordRecTy::get(*i);
411 RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
413 if (NewType2 != SuperRecTy2) {
424 //===----------------------------------------------------------------------===//
425 // Initializer implementations
426 //===----------------------------------------------------------------------===//
428 void Init::anchor() { }
429 void Init::dump() const { return print(errs()); }
431 void UnsetInit::anchor() { }
433 UnsetInit *UnsetInit::get() {
434 static UnsetInit TheInit;
438 void BitInit::anchor() { }
440 BitInit *BitInit::get(bool V) {
441 static BitInit True(true);
442 static BitInit False(false);
444 return V ? &True : &False;
448 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
449 ID.AddInteger(Range.size());
451 for (ArrayRef<Init *>::iterator i = Range.begin(),
458 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
459 typedef FoldingSet<BitsInit> Pool;
463 ProfileBitsInit(ID, Range);
466 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
469 BitsInit *I = new BitsInit(Range);
470 ThePool.InsertNode(I, IP);
475 void BitsInit::Profile(FoldingSetNodeID &ID) const {
476 ProfileBitsInit(ID, Bits);
480 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
481 SmallVector<Init *, 16> NewBits(Bits.size());
483 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
484 if (Bits[i] >= getNumBits())
486 NewBits[i] = getBit(Bits[i]);
488 return BitsInit::get(NewBits);
491 std::string BitsInit::getAsString() const {
492 std::string Result = "{ ";
493 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
494 if (i) Result += ", ";
495 if (Init *Bit = getBit(e-i-1))
496 Result += Bit->getAsString();
500 return Result + " }";
503 // Fix bit initializer to preserve the behavior that bit reference from a unset
504 // bits initializer will resolve into VarBitInit to keep the field name and bit
505 // number used in targets with fixed insn length.
506 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
507 if (RV || After != UnsetInit::get())
512 // resolveReferences - If there are any field references that refer to fields
513 // that have been filled in, we can propagate the values now.
515 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
516 bool Changed = false;
517 SmallVector<Init *, 16> NewBits(getNumBits());
519 Init *CachedInit = nullptr;
520 Init *CachedBitVar = nullptr;
521 bool CachedBitVarChanged = false;
523 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
524 Init *CurBit = Bits[i];
525 Init *CurBitVar = CurBit->getBitVar();
529 if (CurBitVar == CachedBitVar) {
530 if (CachedBitVarChanged) {
531 Init *Bit = CachedInit->getBit(CurBit->getBitNum());
532 NewBits[i] = fixBitInit(RV, CurBit, Bit);
536 CachedBitVar = CurBitVar;
537 CachedBitVarChanged = false;
542 CurBitVar = CurBitVar->resolveReferences(R, RV);
543 CachedBitVarChanged |= B != CurBitVar;
544 Changed |= B != CurBitVar;
545 } while (B != CurBitVar);
546 CachedInit = CurBitVar;
548 if (CachedBitVarChanged) {
549 Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
550 NewBits[i] = fixBitInit(RV, CurBit, Bit);
555 return BitsInit::get(NewBits);
557 return const_cast<BitsInit *>(this);
562 class Pool : public T {
568 for (typename T::iterator I = this->begin(), E = this->end(); I != E; ++I) {
569 typename T::value_type &Item = *I;
575 IntInit *IntInit::get(int64_t V) {
576 static Pool<DenseMap<int64_t, IntInit *> > ThePool;
578 IntInit *&I = ThePool[V];
579 if (!I) I = new IntInit(V);
583 std::string IntInit::getAsString() const {
584 return itostr(Value);
588 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
589 SmallVector<Init *, 16> NewBits(Bits.size());
591 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
595 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
597 return BitsInit::get(NewBits);
600 void StringInit::anchor() { }
602 StringInit *StringInit::get(StringRef V) {
603 static Pool<StringMap<StringInit *> > ThePool;
605 StringInit *&I = ThePool[V];
606 if (!I) I = new StringInit(V);
610 static void ProfileListInit(FoldingSetNodeID &ID,
611 ArrayRef<Init *> Range,
613 ID.AddInteger(Range.size());
614 ID.AddPointer(EltTy);
616 for (ArrayRef<Init *>::iterator i = Range.begin(),
623 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
624 typedef FoldingSet<ListInit> Pool;
627 // Just use the FoldingSetNodeID to compute a hash. Use a DenseMap
628 // for actual storage.
630 ProfileListInit(ID, Range, EltTy);
633 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
636 ListInit *I = new ListInit(Range, EltTy);
637 ThePool.InsertNode(I, IP);
641 void ListInit::Profile(FoldingSetNodeID &ID) const {
642 ListRecTy *ListType = dyn_cast<ListRecTy>(getType());
643 assert(ListType && "Bad type for ListInit!");
644 RecTy *EltTy = ListType->getElementType();
646 ProfileListInit(ID, Values, EltTy);
650 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
651 std::vector<Init*> Vals;
652 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
653 if (Elements[i] >= getSize())
655 Vals.push_back(getElement(Elements[i]));
657 return ListInit::get(Vals, getType());
660 Record *ListInit::getElementAsRecord(unsigned i) const {
661 assert(i < Values.size() && "List element index out of range!");
662 DefInit *DI = dyn_cast<DefInit>(Values[i]);
664 PrintFatalError("Expected record in list!");
668 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
669 std::vector<Init*> Resolved;
670 Resolved.reserve(getSize());
671 bool Changed = false;
673 for (unsigned i = 0, e = getSize(); i != e; ++i) {
675 Init *CurElt = getElement(i);
679 CurElt = CurElt->resolveReferences(R, RV);
680 Changed |= E != CurElt;
681 } while (E != CurElt);
682 Resolved.push_back(E);
686 return ListInit::get(Resolved, getType());
687 return const_cast<ListInit *>(this);
690 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
691 unsigned Elt) const {
692 if (Elt >= getSize())
693 return nullptr; // Out of range reference.
694 Init *E = getElement(Elt);
695 // If the element is set to some value, or if we are resolving a reference
696 // to a specific variable and that variable is explicitly unset, then
697 // replace the VarListElementInit with it.
698 if (IRV || !isa<UnsetInit>(E))
703 std::string ListInit::getAsString() const {
704 std::string Result = "[";
705 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
706 if (i) Result += ", ";
707 Result += Values[i]->getAsString();
712 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
713 unsigned Elt) const {
714 Init *Resolved = resolveReferences(R, IRV);
715 OpInit *OResolved = dyn_cast<OpInit>(Resolved);
717 Resolved = OResolved->Fold(&R, nullptr);
720 if (Resolved != this) {
721 TypedInit *Typed = dyn_cast<TypedInit>(Resolved);
722 assert(Typed && "Expected typed init for list reference");
724 Init *New = Typed->resolveListElementReference(R, IRV, Elt);
727 return VarListElementInit::get(Typed, Elt);
734 Init *OpInit::getBit(unsigned Bit) const {
735 if (getType() == BitRecTy::get())
736 return const_cast<OpInit*>(this);
737 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
740 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
741 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
742 static Pool<DenseMap<Key, UnOpInit *> > ThePool;
744 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
746 UnOpInit *&I = ThePool[TheKey];
747 if (!I) I = new UnOpInit(opc, lhs, Type);
751 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
752 switch (getOpcode()) {
754 if (getType()->getAsString() == "string") {
755 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
758 if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
759 return StringInit::get(LHSd->getDef()->getName());
761 if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
762 return StringInit::get(LHSi->getAsString());
764 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
765 std::string Name = LHSs->getValue();
767 // From TGParser::ParseIDValue
769 if (const RecordVal *RV = CurRec->getValue(Name)) {
770 if (RV->getType() != getType())
771 PrintFatalError("type mismatch in cast");
772 return VarInit::get(Name, RV->getType());
775 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
778 if (CurRec->isTemplateArg(TemplateArgName)) {
779 const RecordVal *RV = CurRec->getValue(TemplateArgName);
780 assert(RV && "Template arg doesn't exist??");
782 if (RV->getType() != getType())
783 PrintFatalError("type mismatch in cast");
785 return VarInit::get(TemplateArgName, RV->getType());
790 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
792 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
793 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
794 assert(RV && "Template arg doesn't exist??");
796 if (RV->getType() != getType())
797 PrintFatalError("type mismatch in cast");
799 return VarInit::get(MCName, RV->getType());
803 if (Record *D = (CurRec->getRecords()).getDef(Name))
804 return DefInit::get(D);
806 PrintFatalError(CurRec->getLoc(),
807 "Undefined reference:'" + Name + "'\n");
813 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
814 if (LHSl->getSize() == 0) {
815 assert(0 && "Empty list in car");
818 return LHSl->getElement(0);
823 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
824 if (LHSl->getSize() == 0) {
825 assert(0 && "Empty list in cdr");
828 // Note the +1. We can't just pass the result of getValues()
830 ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
831 ArrayRef<Init *>::iterator end = LHSl->getValues().end();
833 ListInit::get(ArrayRef<Init *>(begin, end - begin),
840 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
841 if (LHSl->getSize() == 0) {
842 return IntInit::get(1);
844 return IntInit::get(0);
847 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
848 if (LHSs->getValue().empty()) {
849 return IntInit::get(1);
851 return IntInit::get(0);
858 return const_cast<UnOpInit *>(this);
861 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
862 Init *lhs = LHS->resolveReferences(R, RV);
865 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, nullptr);
866 return Fold(&R, nullptr);
869 std::string UnOpInit::getAsString() const {
872 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
873 case HEAD: Result = "!head"; break;
874 case TAIL: Result = "!tail"; break;
875 case EMPTY: Result = "!empty"; break;
877 return Result + "(" + LHS->getAsString() + ")";
880 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
881 Init *rhs, RecTy *Type) {
883 std::pair<std::pair<unsigned, Init *>, Init *>,
887 static Pool<DenseMap<Key, BinOpInit *> > ThePool;
889 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
892 BinOpInit *&I = ThePool[TheKey];
893 if (!I) I = new BinOpInit(opc, lhs, rhs, Type);
897 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
898 switch (getOpcode()) {
900 DagInit *LHSs = dyn_cast<DagInit>(LHS);
901 DagInit *RHSs = dyn_cast<DagInit>(RHS);
903 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
904 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
905 if (!LOp || !ROp || LOp->getDef() != ROp->getDef())
906 PrintFatalError("Concated Dag operators do not match!");
907 std::vector<Init*> Args;
908 std::vector<std::string> ArgNames;
909 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
910 Args.push_back(LHSs->getArg(i));
911 ArgNames.push_back(LHSs->getArgName(i));
913 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
914 Args.push_back(RHSs->getArg(i));
915 ArgNames.push_back(RHSs->getArgName(i));
917 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
922 StringInit *LHSs = dyn_cast<StringInit>(LHS);
923 StringInit *RHSs = dyn_cast<StringInit>(RHS);
925 return StringInit::get(LHSs->getValue() + RHSs->getValue());
929 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
930 // to string objects.
932 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
934 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
937 return IntInit::get(L->getValue() == R->getValue());
939 StringInit *LHSs = dyn_cast<StringInit>(LHS);
940 StringInit *RHSs = dyn_cast<StringInit>(RHS);
942 // Make sure we've resolved
944 return IntInit::get(LHSs->getValue() == RHSs->getValue());
952 IntInit *LHSi = dyn_cast<IntInit>(LHS);
953 IntInit *RHSi = dyn_cast<IntInit>(RHS);
955 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
957 switch (getOpcode()) {
958 default: llvm_unreachable("Bad opcode!");
959 case ADD: Result = LHSv + RHSv; break;
960 case SHL: Result = LHSv << RHSv; break;
961 case SRA: Result = LHSv >> RHSv; break;
962 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
964 return IntInit::get(Result);
969 return const_cast<BinOpInit *>(this);
972 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
973 Init *lhs = LHS->resolveReferences(R, RV);
974 Init *rhs = RHS->resolveReferences(R, RV);
976 if (LHS != lhs || RHS != rhs)
977 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R,nullptr);
978 return Fold(&R, nullptr);
981 std::string BinOpInit::getAsString() const {
984 case CONCAT: Result = "!con"; break;
985 case ADD: Result = "!add"; break;
986 case SHL: Result = "!shl"; break;
987 case SRA: Result = "!sra"; break;
988 case SRL: Result = "!srl"; break;
989 case EQ: Result = "!eq"; break;
990 case STRCONCAT: Result = "!strconcat"; break;
992 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
995 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs,
996 Init *mhs, Init *rhs,
1000 std::pair<std::pair<unsigned, RecTy *>, Init *>,
1006 typedef DenseMap<Key, TernOpInit *> Pool;
1007 static Pool ThePool;
1009 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
1015 TernOpInit *&I = ThePool[TheKey];
1016 if (!I) I = new TernOpInit(opc, lhs, mhs, rhs, Type);
1020 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1021 Record *CurRec, MultiClass *CurMultiClass);
1023 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
1024 RecTy *Type, Record *CurRec,
1025 MultiClass *CurMultiClass) {
1026 std::vector<Init *> NewOperands;
1028 TypedInit *TArg = dyn_cast<TypedInit>(Arg);
1030 // If this is a dag, recurse
1031 if (TArg && TArg->getType()->getAsString() == "dag") {
1032 Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
1033 CurRec, CurMultiClass);
1037 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
1038 OpInit *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i));
1041 Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1042 Type, CurRec, CurMultiClass);
1044 NewOperands.push_back(Result);
1046 NewOperands.push_back(Arg);
1048 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1049 NewOperands.push_back(Arg);
1051 NewOperands.push_back(RHSo->getOperand(i));
1055 // Now run the operator and use its result as the new leaf
1056 const OpInit *NewOp = RHSo->clone(NewOperands);
1057 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
1058 return (NewVal != NewOp) ? NewVal : nullptr;
1061 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1062 Record *CurRec, MultiClass *CurMultiClass) {
1063 DagInit *MHSd = dyn_cast<DagInit>(MHS);
1064 ListInit *MHSl = dyn_cast<ListInit>(MHS);
1066 OpInit *RHSo = dyn_cast<OpInit>(RHS);
1069 PrintFatalError(CurRec->getLoc(), "!foreach requires an operator\n");
1072 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1075 PrintFatalError(CurRec->getLoc(), "!foreach requires typed variable\n");
1077 if ((MHSd && isa<DagRecTy>(Type)) || (MHSl && isa<ListRecTy>(Type))) {
1079 Init *Val = MHSd->getOperator();
1080 Init *Result = EvaluateOperation(RHSo, LHS, Val,
1081 Type, CurRec, CurMultiClass);
1086 std::vector<std::pair<Init *, std::string> > args;
1087 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1089 std::string ArgName;
1090 Arg = MHSd->getArg(i);
1091 ArgName = MHSd->getArgName(i);
1094 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1095 CurRec, CurMultiClass);
1100 // TODO: Process arg names
1101 args.push_back(std::make_pair(Arg, ArgName));
1104 return DagInit::get(Val, "", args);
1107 std::vector<Init *> NewOperands;
1108 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1110 for (std::vector<Init *>::iterator li = NewList.begin(),
1111 liend = NewList.end();
1115 NewOperands.clear();
1116 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1117 // First, replace the foreach variable with the list item
1118 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1119 NewOperands.push_back(Item);
1121 NewOperands.push_back(RHSo->getOperand(i));
1125 // Now run the operator and use its result as the new list item
1126 const OpInit *NewOp = RHSo->clone(NewOperands);
1127 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1128 if (NewItem != NewOp)
1131 return ListInit::get(NewList, MHSl->getType());
1137 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1138 switch (getOpcode()) {
1140 DefInit *LHSd = dyn_cast<DefInit>(LHS);
1141 VarInit *LHSv = dyn_cast<VarInit>(LHS);
1142 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1144 DefInit *MHSd = dyn_cast<DefInit>(MHS);
1145 VarInit *MHSv = dyn_cast<VarInit>(MHS);
1146 StringInit *MHSs = dyn_cast<StringInit>(MHS);
1148 DefInit *RHSd = dyn_cast<DefInit>(RHS);
1149 VarInit *RHSv = dyn_cast<VarInit>(RHS);
1150 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1152 if ((LHSd && MHSd && RHSd)
1153 || (LHSv && MHSv && RHSv)
1154 || (LHSs && MHSs && RHSs)) {
1156 Record *Val = RHSd->getDef();
1157 if (LHSd->getAsString() == RHSd->getAsString()) {
1158 Val = MHSd->getDef();
1160 return DefInit::get(Val);
1163 std::string Val = RHSv->getName();
1164 if (LHSv->getAsString() == RHSv->getAsString()) {
1165 Val = MHSv->getName();
1167 return VarInit::get(Val, getType());
1170 std::string Val = RHSs->getValue();
1172 std::string::size_type found;
1173 std::string::size_type idx = 0;
1175 found = Val.find(LHSs->getValue(), idx);
1176 if (found != std::string::npos) {
1177 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1179 idx = found + MHSs->getValue().size();
1180 } while (found != std::string::npos);
1182 return StringInit::get(Val);
1189 Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1190 CurRec, CurMultiClass);
1198 IntInit *LHSi = dyn_cast<IntInit>(LHS);
1199 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1200 LHSi = dyn_cast<IntInit>(I);
1202 if (LHSi->getValue()) {
1212 return const_cast<TernOpInit *>(this);
1215 Init *TernOpInit::resolveReferences(Record &R,
1216 const RecordVal *RV) const {
1217 Init *lhs = LHS->resolveReferences(R, RV);
1219 if (Opc == IF && lhs != LHS) {
1220 IntInit *Value = dyn_cast<IntInit>(lhs);
1221 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1222 Value = dyn_cast<IntInit>(I);
1225 if (Value->getValue()) {
1226 Init *mhs = MHS->resolveReferences(R, RV);
1227 return (TernOpInit::get(getOpcode(), lhs, mhs,
1228 RHS, getType()))->Fold(&R, nullptr);
1230 Init *rhs = RHS->resolveReferences(R, RV);
1231 return (TernOpInit::get(getOpcode(), lhs, MHS,
1232 rhs, getType()))->Fold(&R, nullptr);
1237 Init *mhs = MHS->resolveReferences(R, RV);
1238 Init *rhs = RHS->resolveReferences(R, RV);
1240 if (LHS != lhs || MHS != mhs || RHS != rhs)
1241 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1242 getType()))->Fold(&R, nullptr);
1243 return Fold(&R, nullptr);
1246 std::string TernOpInit::getAsString() const {
1249 case SUBST: Result = "!subst"; break;
1250 case FOREACH: Result = "!foreach"; break;
1251 case IF: Result = "!if"; break;
1253 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
1254 + RHS->getAsString() + ")";
1257 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1258 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
1259 if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
1260 return Field->getType();
1265 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1266 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1267 if (!T) return nullptr; // Cannot subscript a non-bits variable.
1268 unsigned NumBits = T->getNumBits();
1270 SmallVector<Init *, 16> NewBits(Bits.size());
1271 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1272 if (Bits[i] >= NumBits)
1275 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1277 return BitsInit::get(NewBits);
1281 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1282 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1283 if (!T) return nullptr; // Cannot subscript a non-list variable.
1285 if (Elements.size() == 1)
1286 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1288 std::vector<Init*> ListInits;
1289 ListInits.reserve(Elements.size());
1290 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1291 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1293 return ListInit::get(ListInits, T);
1297 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1298 Init *Value = StringInit::get(VN);
1299 return VarInit::get(Value, T);
1302 VarInit *VarInit::get(Init *VN, RecTy *T) {
1303 typedef std::pair<RecTy *, Init *> Key;
1304 static Pool<DenseMap<Key, VarInit *> > ThePool;
1306 Key TheKey(std::make_pair(T, VN));
1308 VarInit *&I = ThePool[TheKey];
1309 if (!I) I = new VarInit(VN, T);
1313 const std::string &VarInit::getName() const {
1314 StringInit *NameString = dyn_cast<StringInit>(getNameInit());
1315 assert(NameString && "VarInit name is not a string!");
1316 return NameString->getValue();
1319 Init *VarInit::getBit(unsigned Bit) const {
1320 if (getType() == BitRecTy::get())
1321 return const_cast<VarInit*>(this);
1322 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1325 Init *VarInit::resolveListElementReference(Record &R,
1326 const RecordVal *IRV,
1327 unsigned Elt) const {
1328 if (R.isTemplateArg(getNameInit())) return nullptr;
1329 if (IRV && IRV->getNameInit() != getNameInit()) return nullptr;
1331 RecordVal *RV = R.getValue(getNameInit());
1332 assert(RV && "Reference to a non-existent variable?");
1333 ListInit *LI = dyn_cast<ListInit>(RV->getValue());
1335 TypedInit *VI = dyn_cast<TypedInit>(RV->getValue());
1336 assert(VI && "Invalid list element!");
1337 return VarListElementInit::get(VI, Elt);
1340 if (Elt >= LI->getSize())
1341 return nullptr; // Out of range reference.
1342 Init *E = LI->getElement(Elt);
1343 // If the element is set to some value, or if we are resolving a reference
1344 // to a specific variable and that variable is explicitly unset, then
1345 // replace the VarListElementInit with it.
1346 if (IRV || !isa<UnsetInit>(E))
1352 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1353 if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
1354 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1355 return RV->getType();
1359 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1360 const std::string &FieldName) const {
1361 if (isa<RecordRecTy>(getType()))
1362 if (const RecordVal *Val = R.getValue(VarName)) {
1363 if (RV != Val && (RV || isa<UnsetInit>(Val->getValue())))
1365 Init *TheInit = Val->getValue();
1366 assert(TheInit != this && "Infinite loop detected!");
1367 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1375 /// resolveReferences - This method is used by classes that refer to other
1376 /// variables which may not be defined at the time the expression is formed.
1377 /// If a value is set for the variable later, this method will be called on
1378 /// users of the value to allow the value to propagate out.
1380 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1381 if (RecordVal *Val = R.getValue(VarName))
1382 if (RV == Val || (!RV && !isa<UnsetInit>(Val->getValue())))
1383 return Val->getValue();
1384 return const_cast<VarInit *>(this);
1387 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1388 typedef std::pair<TypedInit *, unsigned> Key;
1389 typedef DenseMap<Key, VarBitInit *> Pool;
1391 static Pool ThePool;
1393 Key TheKey(std::make_pair(T, B));
1395 VarBitInit *&I = ThePool[TheKey];
1396 if (!I) I = new VarBitInit(T, B);
1400 std::string VarBitInit::getAsString() const {
1401 return TI->getAsString() + "{" + utostr(Bit) + "}";
1404 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1405 Init *I = TI->resolveReferences(R, RV);
1407 return I->getBit(getBitNum());
1409 return const_cast<VarBitInit*>(this);
1412 VarListElementInit *VarListElementInit::get(TypedInit *T,
1414 typedef std::pair<TypedInit *, unsigned> Key;
1415 typedef DenseMap<Key, VarListElementInit *> Pool;
1417 static Pool ThePool;
1419 Key TheKey(std::make_pair(T, E));
1421 VarListElementInit *&I = ThePool[TheKey];
1422 if (!I) I = new VarListElementInit(T, E);
1426 std::string VarListElementInit::getAsString() const {
1427 return TI->getAsString() + "[" + utostr(Element) + "]";
1431 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1432 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1435 return const_cast<VarListElementInit *>(this);
1438 Init *VarListElementInit::getBit(unsigned Bit) const {
1439 if (getType() == BitRecTy::get())
1440 return const_cast<VarListElementInit*>(this);
1441 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1444 Init *VarListElementInit:: resolveListElementReference(Record &R,
1445 const RecordVal *RV,
1446 unsigned Elt) const {
1447 Init *Result = TI->resolveListElementReference(R, RV, Element);
1450 if (TypedInit *TInit = dyn_cast<TypedInit>(Result)) {
1451 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1452 if (Result2) return Result2;
1453 return new VarListElementInit(TInit, Elt);
1461 DefInit *DefInit::get(Record *R) {
1462 return R->getDefInit();
1465 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1466 if (const RecordVal *RV = Def->getValue(FieldName))
1467 return RV->getType();
1471 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1472 const std::string &FieldName) const {
1473 return Def->getValue(FieldName)->getValue();
1477 std::string DefInit::getAsString() const {
1478 return Def->getName();
1481 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1482 typedef std::pair<Init *, TableGenStringKey> Key;
1483 typedef DenseMap<Key, FieldInit *> Pool;
1484 static Pool ThePool;
1486 Key TheKey(std::make_pair(R, FN));
1488 FieldInit *&I = ThePool[TheKey];
1489 if (!I) I = new FieldInit(R, FN);
1493 Init *FieldInit::getBit(unsigned Bit) const {
1494 if (getType() == BitRecTy::get())
1495 return const_cast<FieldInit*>(this);
1496 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1499 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1500 unsigned Elt) const {
1501 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1502 if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
1503 if (Elt >= LI->getSize()) return nullptr;
1504 Init *E = LI->getElement(Elt);
1506 // If the element is set to some value, or if we are resolving a
1507 // reference to a specific variable and that variable is explicitly
1508 // unset, then replace the VarListElementInit with it.
1509 if (RV || !isa<UnsetInit>(E))
1515 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1516 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1518 Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1520 Init *BVR = BitsVal->resolveReferences(R, RV);
1521 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1524 if (NewRec != Rec) {
1525 return FieldInit::get(NewRec, FieldName);
1527 return const_cast<FieldInit *>(this);
1530 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, const std::string &VN,
1531 ArrayRef<Init *> ArgRange,
1532 ArrayRef<std::string> NameRange) {
1536 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1537 ArrayRef<std::string>::iterator Name = NameRange.begin();
1538 while (Arg != ArgRange.end()) {
1539 assert(Name != NameRange.end() && "Arg name underflow!");
1540 ID.AddPointer(*Arg++);
1541 ID.AddString(*Name++);
1543 assert(Name == NameRange.end() && "Arg name overflow!");
1547 DagInit::get(Init *V, const std::string &VN,
1548 ArrayRef<Init *> ArgRange,
1549 ArrayRef<std::string> NameRange) {
1550 typedef FoldingSet<DagInit> Pool;
1551 static Pool ThePool;
1553 FoldingSetNodeID ID;
1554 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1557 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1560 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1561 ThePool.InsertNode(I, IP);
1567 DagInit::get(Init *V, const std::string &VN,
1568 const std::vector<std::pair<Init*, std::string> > &args) {
1569 typedef std::pair<Init*, std::string> PairType;
1571 std::vector<Init *> Args;
1572 std::vector<std::string> Names;
1574 for (std::vector<PairType>::const_iterator i = args.begin(),
1578 Args.push_back(i->first);
1579 Names.push_back(i->second);
1582 return DagInit::get(V, VN, Args, Names);
1585 void DagInit::Profile(FoldingSetNodeID &ID) const {
1586 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1589 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1590 std::vector<Init*> NewArgs;
1591 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1592 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1594 Init *Op = Val->resolveReferences(R, RV);
1596 if (Args != NewArgs || Op != Val)
1597 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1599 return const_cast<DagInit *>(this);
1603 std::string DagInit::getAsString() const {
1604 std::string Result = "(" + Val->getAsString();
1605 if (!ValName.empty())
1606 Result += ":" + ValName;
1608 Result += " " + Args[0]->getAsString();
1609 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1610 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1611 Result += ", " + Args[i]->getAsString();
1612 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1615 return Result + ")";
1619 //===----------------------------------------------------------------------===//
1620 // Other implementations
1621 //===----------------------------------------------------------------------===//
1623 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1624 : Name(N), Ty(T), Prefix(P) {
1625 Value = Ty->convertValue(UnsetInit::get());
1626 assert(Value && "Cannot create unset value for current type!");
1629 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1630 : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1631 Value = Ty->convertValue(UnsetInit::get());
1632 assert(Value && "Cannot create unset value for current type!");
1635 const std::string &RecordVal::getName() const {
1636 StringInit *NameString = dyn_cast<StringInit>(Name);
1637 assert(NameString && "RecordVal name is not a string!");
1638 return NameString->getValue();
1641 void RecordVal::dump() const { errs() << *this; }
1643 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1644 if (getPrefix()) OS << "field ";
1645 OS << *getType() << " " << getNameInitAsString();
1648 OS << " = " << *getValue();
1650 if (PrintSem) OS << ";\n";
1653 unsigned Record::LastID = 0;
1655 void Record::init() {
1658 // Every record potentially has a def at the top. This value is
1659 // replaced with the top-level def name at instantiation time.
1660 RecordVal DN("NAME", StringRecTy::get(), 0);
1664 void Record::checkName() {
1665 // Ensure the record name has string type.
1666 const TypedInit *TypedName = dyn_cast<const TypedInit>(Name);
1667 assert(TypedName && "Record name is not typed!");
1668 RecTy *Type = TypedName->getType();
1669 if (!isa<StringRecTy>(Type))
1670 PrintFatalError(getLoc(), "Record name is not a string!");
1673 DefInit *Record::getDefInit() {
1675 TheInit = new DefInit(this, new RecordRecTy(this));
1679 const std::string &Record::getName() const {
1680 const StringInit *NameString = dyn_cast<StringInit>(Name);
1681 assert(NameString && "Record name is not a string!");
1682 return NameString->getValue();
1685 void Record::setName(Init *NewName) {
1686 if (TrackedRecords.getDef(Name->getAsUnquotedString()) == this) {
1687 TrackedRecords.removeDef(Name->getAsUnquotedString());
1688 TrackedRecords.addDef(this);
1689 } else if (TrackedRecords.getClass(Name->getAsUnquotedString()) == this) {
1690 TrackedRecords.removeClass(Name->getAsUnquotedString());
1691 TrackedRecords.addClass(this);
1692 } // Otherwise this isn't yet registered.
1695 // DO NOT resolve record values to the name at this point because
1696 // there might be default values for arguments of this def. Those
1697 // arguments might not have been resolved yet so we don't want to
1698 // prematurely assume values for those arguments were not passed to
1701 // Nonetheless, it may be that some of this Record's values
1702 // reference the record name. Indeed, the reason for having the
1703 // record name be an Init is to provide this flexibility. The extra
1704 // resolve steps after completely instantiating defs takes care of
1705 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1708 void Record::setName(const std::string &Name) {
1709 setName(StringInit::get(Name));
1712 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1713 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1715 void Record::resolveReferencesTo(const RecordVal *RV) {
1716 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1717 if (RV == &Values[i]) // Skip resolve the same field as the given one
1719 if (Init *V = Values[i].getValue())
1720 if (Values[i].setValue(V->resolveReferences(*this, RV)))
1721 PrintFatalError(getLoc(), "Invalid value is found when setting '"
1722 + Values[i].getNameInitAsString()
1723 + "' after resolving references"
1724 + (RV ? " against '" + RV->getNameInitAsString()
1726 + RV->getValue()->getAsUnquotedString() + ")"
1730 Init *OldName = getNameInit();
1731 Init *NewName = Name->resolveReferences(*this, RV);
1732 if (NewName != OldName) {
1733 // Re-register with RecordKeeper.
1738 void Record::dump() const { errs() << *this; }
1740 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1741 OS << R.getNameInitAsString();
1743 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1744 if (!TArgs.empty()) {
1746 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1748 const RecordVal *RV = R.getValue(TArgs[i]);
1749 assert(RV && "Template argument record not found??");
1750 RV->print(OS, false);
1756 const std::vector<Record*> &SC = R.getSuperClasses();
1759 for (unsigned i = 0, e = SC.size(); i != e; ++i)
1760 OS << " " << SC[i]->getNameInitAsString();
1764 const std::vector<RecordVal> &Vals = R.getValues();
1765 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1766 if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1768 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1769 if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1775 /// getValueInit - Return the initializer for a value with the specified name,
1776 /// or abort if the field does not exist.
1778 Init *Record::getValueInit(StringRef FieldName) const {
1779 const RecordVal *R = getValue(FieldName);
1780 if (!R || !R->getValue())
1781 PrintFatalError(getLoc(), "Record `" + getName() +
1782 "' does not have a field named `" + FieldName + "'!\n");
1783 return R->getValue();
1787 /// getValueAsString - This method looks up the specified field and returns its
1788 /// value as a string, aborts if the field does not exist or if
1789 /// the value is not a string.
1791 std::string Record::getValueAsString(StringRef FieldName) const {
1792 const RecordVal *R = getValue(FieldName);
1793 if (!R || !R->getValue())
1794 PrintFatalError(getLoc(), "Record `" + getName() +
1795 "' does not have a field named `" + FieldName + "'!\n");
1797 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1798 return SI->getValue();
1799 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1800 FieldName + "' does not have a string initializer!");
1803 /// getValueAsBitsInit - This method looks up the specified field and returns
1804 /// its value as a BitsInit, aborts if the field does not exist or if
1805 /// the value is not the right type.
1807 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1808 const RecordVal *R = getValue(FieldName);
1809 if (!R || !R->getValue())
1810 PrintFatalError(getLoc(), "Record `" + getName() +
1811 "' does not have a field named `" + FieldName + "'!\n");
1813 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
1815 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1816 FieldName + "' does not have a BitsInit initializer!");
1819 /// getValueAsListInit - This method looks up the specified field and returns
1820 /// its value as a ListInit, aborting if the field does not exist or if
1821 /// the value is not the right type.
1823 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1824 const RecordVal *R = getValue(FieldName);
1825 if (!R || !R->getValue())
1826 PrintFatalError(getLoc(), "Record `" + getName() +
1827 "' does not have a field named `" + FieldName + "'!\n");
1829 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
1831 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1832 FieldName + "' does not have a list initializer!");
1835 /// getValueAsListOfDefs - This method looks up the specified field and returns
1836 /// its value as a vector of records, aborting if the field does not exist
1837 /// or if the value is not the right type.
1839 std::vector<Record*>
1840 Record::getValueAsListOfDefs(StringRef FieldName) const {
1841 ListInit *List = getValueAsListInit(FieldName);
1842 std::vector<Record*> Defs;
1843 for (unsigned i = 0; i < List->getSize(); i++) {
1844 if (DefInit *DI = dyn_cast<DefInit>(List->getElement(i))) {
1845 Defs.push_back(DI->getDef());
1847 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1848 FieldName + "' list is not entirely DefInit!");
1854 /// getValueAsInt - This method looks up the specified field and returns its
1855 /// value as an int64_t, aborting if the field does not exist or if the value
1856 /// is not the right type.
1858 int64_t Record::getValueAsInt(StringRef FieldName) 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 + "'!\n");
1864 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
1865 return II->getValue();
1866 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1867 FieldName + "' does not have an int initializer!");
1870 /// getValueAsListOfInts - This method looks up the specified field and returns
1871 /// its value as a vector of integers, aborting if the field does not exist or
1872 /// if the value is not the right type.
1874 std::vector<int64_t>
1875 Record::getValueAsListOfInts(StringRef FieldName) const {
1876 ListInit *List = getValueAsListInit(FieldName);
1877 std::vector<int64_t> Ints;
1878 for (unsigned i = 0; i < List->getSize(); i++) {
1879 if (IntInit *II = dyn_cast<IntInit>(List->getElement(i))) {
1880 Ints.push_back(II->getValue());
1882 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1883 FieldName + "' does not have a list of ints initializer!");
1889 /// getValueAsListOfStrings - This method looks up the specified field and
1890 /// returns its value as a vector of strings, aborting if the field does not
1891 /// exist or if the value is not the right type.
1893 std::vector<std::string>
1894 Record::getValueAsListOfStrings(StringRef FieldName) const {
1895 ListInit *List = getValueAsListInit(FieldName);
1896 std::vector<std::string> Strings;
1897 for (unsigned i = 0; i < List->getSize(); i++) {
1898 if (StringInit *II = dyn_cast<StringInit>(List->getElement(i))) {
1899 Strings.push_back(II->getValue());
1901 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1902 FieldName + "' does not have a list of strings initializer!");
1908 /// getValueAsDef - This method looks up the specified field and returns its
1909 /// value as a Record, aborting if the field does not exist or if the value
1910 /// is not the right type.
1912 Record *Record::getValueAsDef(StringRef FieldName) const {
1913 const RecordVal *R = getValue(FieldName);
1914 if (!R || !R->getValue())
1915 PrintFatalError(getLoc(), "Record `" + getName() +
1916 "' does not have a field named `" + FieldName + "'!\n");
1918 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
1919 return DI->getDef();
1920 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1921 FieldName + "' does not have a def initializer!");
1924 /// getValueAsBit - This method looks up the specified field and returns its
1925 /// value as a bit, aborting if the field does not exist or if the value is
1926 /// not the right type.
1928 bool Record::getValueAsBit(StringRef FieldName) const {
1929 const RecordVal *R = getValue(FieldName);
1930 if (!R || !R->getValue())
1931 PrintFatalError(getLoc(), "Record `" + getName() +
1932 "' does not have a field named `" + FieldName + "'!\n");
1934 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1935 return BI->getValue();
1936 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1937 FieldName + "' does not have a bit initializer!");
1940 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1941 const RecordVal *R = getValue(FieldName);
1942 if (!R || !R->getValue())
1943 PrintFatalError(getLoc(), "Record `" + getName() +
1944 "' does not have a field named `" + FieldName.str() + "'!\n");
1946 if (R->getValue() == UnsetInit::get()) {
1951 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1952 return BI->getValue();
1953 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1954 FieldName + "' does not have a bit initializer!");
1957 /// getValueAsDag - This method looks up the specified field and returns its
1958 /// value as an Dag, aborting if the field does not exist or if the value is
1959 /// not the right type.
1961 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1962 const RecordVal *R = getValue(FieldName);
1963 if (!R || !R->getValue())
1964 PrintFatalError(getLoc(), "Record `" + getName() +
1965 "' does not have a field named `" + FieldName + "'!\n");
1967 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
1969 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1970 FieldName + "' does not have a dag initializer!");
1974 void MultiClass::dump() const {
1975 errs() << "Record:\n";
1978 errs() << "Defs:\n";
1979 for (RecordVector::const_iterator r = DefPrototypes.begin(),
1980 rend = DefPrototypes.end();
1988 void RecordKeeper::dump() const { errs() << *this; }
1990 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1991 OS << "------------- Classes -----------------\n";
1992 const std::map<std::string, Record*> &Classes = RK.getClasses();
1993 for (std::map<std::string, Record*>::const_iterator I = Classes.begin(),
1994 E = Classes.end(); I != E; ++I)
1995 OS << "class " << *I->second;
1997 OS << "------------- Defs -----------------\n";
1998 const std::map<std::string, Record*> &Defs = RK.getDefs();
1999 for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),
2000 E = Defs.end(); I != E; ++I)
2001 OS << "def " << *I->second;
2006 /// getAllDerivedDefinitions - This method returns all concrete definitions
2007 /// that derive from the specified class name. If a class with the specified
2008 /// name does not exist, an error is printed and true is returned.
2009 std::vector<Record*>
2010 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
2011 Record *Class = getClass(ClassName);
2013 PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
2015 std::vector<Record*> Defs;
2016 for (std::map<std::string, Record*>::const_iterator I = getDefs().begin(),
2017 E = getDefs().end(); I != E; ++I)
2018 if (I->second->isSubClassOf(Class))
2019 Defs.push_back(I->second);
2024 /// QualifyName - Return an Init with a qualifier prefix referring
2025 /// to CurRec's name.
2026 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2027 Init *Name, const std::string &Scoper) {
2028 RecTy *Type = dyn_cast<TypedInit>(Name)->getType();
2030 BinOpInit *NewName =
2031 BinOpInit::get(BinOpInit::STRCONCAT,
2032 BinOpInit::get(BinOpInit::STRCONCAT,
2033 CurRec.getNameInit(),
2034 StringInit::get(Scoper),
2035 Type)->Fold(&CurRec, CurMultiClass),
2039 if (CurMultiClass && Scoper != "::") {
2041 BinOpInit::get(BinOpInit::STRCONCAT,
2042 BinOpInit::get(BinOpInit::STRCONCAT,
2043 CurMultiClass->Rec.getNameInit(),
2044 StringInit::get("::"),
2045 Type)->Fold(&CurRec, CurMultiClass),
2046 NewName->Fold(&CurRec, CurMultiClass),
2050 return NewName->Fold(&CurRec, CurMultiClass);
2053 /// QualifyName - Return an Init with a qualifier prefix referring
2054 /// to CurRec's name.
2055 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2056 const std::string &Name,
2057 const std::string &Scoper) {
2058 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);