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;
125 bool BitRecTy::baseClassOf(const RecTy *RHS) const{
126 if(RecTy::baseClassOf(RHS) || getRecTyKind() == IntRecTyKind)
128 if(const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
129 return BitsTy->getNumBits() == 1;
133 BitsRecTy *BitsRecTy::get(unsigned Sz) {
134 static std::vector<BitsRecTy*> Shared;
135 if (Sz >= Shared.size())
136 Shared.resize(Sz + 1);
137 BitsRecTy *&Ty = Shared[Sz];
139 Ty = new BitsRecTy(Sz);
143 std::string BitsRecTy::getAsString() const {
144 return "bits<" + utostr(Size) + ">";
147 Init *BitsRecTy::convertValue(UnsetInit *UI) {
148 SmallVector<Init *, 16> NewBits(Size);
150 for (unsigned i = 0; i != Size; ++i)
151 NewBits[i] = UnsetInit::get();
153 return BitsInit::get(NewBits);
156 Init *BitsRecTy::convertValue(BitInit *UI) {
157 if (Size != 1) return nullptr; // Can only convert single bit.
158 return BitsInit::get(UI);
161 /// canFitInBitfield - Return true if the number of bits is large enough to hold
162 /// the integer value.
163 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
164 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
165 return (NumBits >= sizeof(Value) * 8) ||
166 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
169 /// convertValue from Int initializer to bits type: Split the integer up into the
170 /// appropriate bits.
172 Init *BitsRecTy::convertValue(IntInit *II) {
173 int64_t Value = II->getValue();
174 // Make sure this bitfield is large enough to hold the integer value.
175 if (!canFitInBitfield(Value, Size))
178 SmallVector<Init *, 16> NewBits(Size);
180 for (unsigned i = 0; i != Size; ++i)
181 NewBits[i] = BitInit::get(Value & (1LL << i));
183 return BitsInit::get(NewBits);
186 Init *BitsRecTy::convertValue(BitsInit *BI) {
187 // If the number of bits is right, return it. Otherwise we need to expand or
189 if (BI->getNumBits() == Size) return BI;
193 Init *BitsRecTy::convertValue(TypedInit *VI) {
194 if (Size == 1 && isa<BitRecTy>(VI->getType()))
195 return BitsInit::get(VI);
197 if (VI->getType()->typeIsConvertibleTo(this)) {
198 SmallVector<Init *, 16> NewBits(Size);
200 for (unsigned i = 0; i != Size; ++i)
201 NewBits[i] = VarBitInit::get(VI, i);
202 return BitsInit::get(NewBits);
208 bool BitsRecTy::baseClassOf(const RecTy *RHS) const{
209 if (RecTy::baseClassOf(RHS)) //argument and the receiver are the same type
210 return cast<BitsRecTy>(RHS)->Size == Size;
211 RecTyKind kind = RHS->getRecTyKind();
212 return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
215 Init *IntRecTy::convertValue(BitInit *BI) {
216 return IntInit::get(BI->getValue());
219 Init *IntRecTy::convertValue(BitsInit *BI) {
221 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
222 if (BitInit *Bit = dyn_cast<BitInit>(BI->getBit(i))) {
223 Result |= Bit->getValue() << i;
227 return IntInit::get(Result);
230 Init *IntRecTy::convertValue(TypedInit *TI) {
231 if (TI->getType()->typeIsConvertibleTo(this))
232 return TI; // Accept variable if already of the right type!
236 bool IntRecTy::baseClassOf(const RecTy *RHS) const{
237 RecTyKind kind = RHS->getRecTyKind();
238 return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
241 Init *StringRecTy::convertValue(UnOpInit *BO) {
242 if (BO->getOpcode() == UnOpInit::CAST) {
243 Init *L = BO->getOperand()->convertInitializerTo(this);
244 if (!L) return nullptr;
245 if (L != BO->getOperand())
246 return UnOpInit::get(UnOpInit::CAST, L, new StringRecTy);
250 return convertValue((TypedInit*)BO);
253 Init *StringRecTy::convertValue(BinOpInit *BO) {
254 if (BO->getOpcode() == BinOpInit::STRCONCAT) {
255 Init *L = BO->getLHS()->convertInitializerTo(this);
256 Init *R = BO->getRHS()->convertInitializerTo(this);
257 if (!L || !R) return nullptr;
258 if (L != BO->getLHS() || R != BO->getRHS())
259 return BinOpInit::get(BinOpInit::STRCONCAT, L, R, new StringRecTy);
263 return convertValue((TypedInit*)BO);
267 Init *StringRecTy::convertValue(TypedInit *TI) {
268 if (isa<StringRecTy>(TI->getType()))
269 return TI; // Accept variable if already of the right type!
273 std::string ListRecTy::getAsString() const {
274 return "list<" + Ty->getAsString() + ">";
277 Init *ListRecTy::convertValue(ListInit *LI) {
278 std::vector<Init*> Elements;
280 // Verify that all of the elements of the list are subclasses of the
281 // appropriate class!
282 for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
283 if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
284 Elements.push_back(CI);
288 if (!isa<ListRecTy>(LI->getType()))
291 return ListInit::get(Elements, this);
294 Init *ListRecTy::convertValue(TypedInit *TI) {
295 // Ensure that TI is compatible with our class.
296 if (ListRecTy *LRT = dyn_cast<ListRecTy>(TI->getType()))
297 if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
302 bool ListRecTy::baseClassOf(const RecTy *RHS) const{
303 if(const ListRecTy* ListTy = dyn_cast<ListRecTy>(RHS))
304 return ListTy->getElementType()->typeIsConvertibleTo(Ty);
308 Init *DagRecTy::convertValue(TypedInit *TI) {
309 if (TI->getType()->typeIsConvertibleTo(this))
314 Init *DagRecTy::convertValue(UnOpInit *BO) {
315 if (BO->getOpcode() == UnOpInit::CAST) {
316 Init *L = BO->getOperand()->convertInitializerTo(this);
317 if (!L) return nullptr;
318 if (L != BO->getOperand())
319 return UnOpInit::get(UnOpInit::CAST, L, new DagRecTy);
325 Init *DagRecTy::convertValue(BinOpInit *BO) {
326 if (BO->getOpcode() == BinOpInit::CONCAT) {
327 Init *L = BO->getLHS()->convertInitializerTo(this);
328 Init *R = BO->getRHS()->convertInitializerTo(this);
329 if (!L || !R) return nullptr;
330 if (L != BO->getLHS() || R != BO->getRHS())
331 return BinOpInit::get(BinOpInit::CONCAT, L, R, new DagRecTy);
337 RecordRecTy *RecordRecTy::get(Record *R) {
338 return dyn_cast<RecordRecTy>(R->getDefInit()->getType());
341 std::string RecordRecTy::getAsString() const {
342 return Rec->getName();
345 Init *RecordRecTy::convertValue(DefInit *DI) {
346 // Ensure that DI is a subclass of Rec.
347 if (!DI->getDef()->isSubClassOf(Rec))
352 Init *RecordRecTy::convertValue(TypedInit *TI) {
353 // Ensure that TI is compatible with Rec.
354 if (RecordRecTy *RRT = dyn_cast<RecordRecTy>(TI->getType()))
355 if (RRT->getRecord()->isSubClassOf(getRecord()) ||
356 RRT->getRecord() == getRecord())
361 bool RecordRecTy::baseClassOf(const RecTy *RHS) const{
362 const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
366 if (Rec == RTy->getRecord() || RTy->getRecord()->isSubClassOf(Rec))
369 const std::vector<Record*> &SC = Rec->getSuperClasses();
370 for (unsigned i = 0, e = SC.size(); i != e; ++i)
371 if (RTy->getRecord()->isSubClassOf(SC[i]))
377 /// resolveTypes - Find a common type that T1 and T2 convert to.
378 /// Return 0 if no such type exists.
380 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
381 if (T1->typeIsConvertibleTo(T2))
383 if (T2->typeIsConvertibleTo(T1))
386 // If one is a Record type, check superclasses
387 if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
388 // See if T2 inherits from a type T1 also inherits from
389 const std::vector<Record *> &T1SuperClasses =
390 RecTy1->getRecord()->getSuperClasses();
391 for(std::vector<Record *>::const_iterator i = T1SuperClasses.begin(),
392 iend = T1SuperClasses.end();
395 RecordRecTy *SuperRecTy1 = RecordRecTy::get(*i);
396 RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
398 if (NewType1 != SuperRecTy1) {
405 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) {
406 // See if T1 inherits from a type T2 also inherits from
407 const std::vector<Record *> &T2SuperClasses =
408 RecTy2->getRecord()->getSuperClasses();
409 for (std::vector<Record *>::const_iterator i = T2SuperClasses.begin(),
410 iend = T2SuperClasses.end();
413 RecordRecTy *SuperRecTy2 = RecordRecTy::get(*i);
414 RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
416 if (NewType2 != SuperRecTy2) {
427 //===----------------------------------------------------------------------===//
428 // Initializer implementations
429 //===----------------------------------------------------------------------===//
431 void Init::anchor() { }
432 void Init::dump() const { return print(errs()); }
434 void UnsetInit::anchor() { }
436 UnsetInit *UnsetInit::get() {
437 static UnsetInit TheInit;
441 void BitInit::anchor() { }
443 BitInit *BitInit::get(bool V) {
444 static BitInit True(true);
445 static BitInit False(false);
447 return V ? &True : &False;
451 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
452 ID.AddInteger(Range.size());
454 for (ArrayRef<Init *>::iterator i = Range.begin(),
461 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
462 typedef FoldingSet<BitsInit> Pool;
466 ProfileBitsInit(ID, Range);
469 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
472 BitsInit *I = new BitsInit(Range);
473 ThePool.InsertNode(I, IP);
478 void BitsInit::Profile(FoldingSetNodeID &ID) const {
479 ProfileBitsInit(ID, Bits);
483 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
484 SmallVector<Init *, 16> NewBits(Bits.size());
486 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
487 if (Bits[i] >= getNumBits())
489 NewBits[i] = getBit(Bits[i]);
491 return BitsInit::get(NewBits);
494 std::string BitsInit::getAsString() const {
495 std::string Result = "{ ";
496 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
497 if (i) Result += ", ";
498 if (Init *Bit = getBit(e-i-1))
499 Result += Bit->getAsString();
503 return Result + " }";
506 // Fix bit initializer to preserve the behavior that bit reference from a unset
507 // bits initializer will resolve into VarBitInit to keep the field name and bit
508 // number used in targets with fixed insn length.
509 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
510 if (RV || After != UnsetInit::get())
515 // resolveReferences - If there are any field references that refer to fields
516 // that have been filled in, we can propagate the values now.
518 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
519 bool Changed = false;
520 SmallVector<Init *, 16> NewBits(getNumBits());
522 Init *CachedInit = nullptr;
523 Init *CachedBitVar = nullptr;
524 bool CachedBitVarChanged = false;
526 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
527 Init *CurBit = Bits[i];
528 Init *CurBitVar = CurBit->getBitVar();
532 if (CurBitVar == CachedBitVar) {
533 if (CachedBitVarChanged) {
534 Init *Bit = CachedInit->getBit(CurBit->getBitNum());
535 NewBits[i] = fixBitInit(RV, CurBit, Bit);
539 CachedBitVar = CurBitVar;
540 CachedBitVarChanged = false;
545 CurBitVar = CurBitVar->resolveReferences(R, RV);
546 CachedBitVarChanged |= B != CurBitVar;
547 Changed |= B != CurBitVar;
548 } while (B != CurBitVar);
549 CachedInit = CurBitVar;
551 if (CachedBitVarChanged) {
552 Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
553 NewBits[i] = fixBitInit(RV, CurBit, Bit);
558 return BitsInit::get(NewBits);
560 return const_cast<BitsInit *>(this);
565 class Pool : public T {
571 for (typename T::iterator I = this->begin(), E = this->end(); I != E; ++I) {
572 typename T::value_type &Item = *I;
578 IntInit *IntInit::get(int64_t V) {
579 static Pool<DenseMap<int64_t, IntInit *> > ThePool;
581 IntInit *&I = ThePool[V];
582 if (!I) I = new IntInit(V);
586 std::string IntInit::getAsString() const {
587 return itostr(Value);
591 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
592 SmallVector<Init *, 16> NewBits(Bits.size());
594 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
598 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
600 return BitsInit::get(NewBits);
603 void StringInit::anchor() { }
605 StringInit *StringInit::get(StringRef V) {
606 static Pool<StringMap<StringInit *> > ThePool;
608 StringInit *&I = ThePool[V];
609 if (!I) I = new StringInit(V);
613 static void ProfileListInit(FoldingSetNodeID &ID,
614 ArrayRef<Init *> Range,
616 ID.AddInteger(Range.size());
617 ID.AddPointer(EltTy);
619 for (ArrayRef<Init *>::iterator i = Range.begin(),
626 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
627 typedef FoldingSet<ListInit> Pool;
629 static std::vector<std::unique_ptr<ListInit>> TheActualPool;
632 ProfileListInit(ID, Range, EltTy);
635 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
638 ListInit *I = new ListInit(Range, EltTy);
639 ThePool.InsertNode(I, IP);
640 TheActualPool.push_back(std::unique_ptr<ListInit>(I));
644 void ListInit::Profile(FoldingSetNodeID &ID) const {
645 ListRecTy *ListType = dyn_cast<ListRecTy>(getType());
646 assert(ListType && "Bad type for ListInit!");
647 RecTy *EltTy = ListType->getElementType();
649 ProfileListInit(ID, Values, EltTy);
653 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
654 std::vector<Init*> Vals;
655 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
656 if (Elements[i] >= getSize())
658 Vals.push_back(getElement(Elements[i]));
660 return ListInit::get(Vals, getType());
663 Record *ListInit::getElementAsRecord(unsigned i) const {
664 assert(i < Values.size() && "List element index out of range!");
665 DefInit *DI = dyn_cast<DefInit>(Values[i]);
667 PrintFatalError("Expected record in list!");
671 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
672 std::vector<Init*> Resolved;
673 Resolved.reserve(getSize());
674 bool Changed = false;
676 for (unsigned i = 0, e = getSize(); i != e; ++i) {
678 Init *CurElt = getElement(i);
682 CurElt = CurElt->resolveReferences(R, RV);
683 Changed |= E != CurElt;
684 } while (E != CurElt);
685 Resolved.push_back(E);
689 return ListInit::get(Resolved, getType());
690 return const_cast<ListInit *>(this);
693 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
694 unsigned Elt) const {
695 if (Elt >= getSize())
696 return nullptr; // Out of range reference.
697 Init *E = getElement(Elt);
698 // If the element is set to some value, or if we are resolving a reference
699 // to a specific variable and that variable is explicitly unset, then
700 // replace the VarListElementInit with it.
701 if (IRV || !isa<UnsetInit>(E))
706 std::string ListInit::getAsString() const {
707 std::string Result = "[";
708 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
709 if (i) Result += ", ";
710 Result += Values[i]->getAsString();
715 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
716 unsigned Elt) const {
717 Init *Resolved = resolveReferences(R, IRV);
718 OpInit *OResolved = dyn_cast<OpInit>(Resolved);
720 Resolved = OResolved->Fold(&R, nullptr);
723 if (Resolved != this) {
724 TypedInit *Typed = dyn_cast<TypedInit>(Resolved);
725 assert(Typed && "Expected typed init for list reference");
727 Init *New = Typed->resolveListElementReference(R, IRV, Elt);
730 return VarListElementInit::get(Typed, Elt);
737 Init *OpInit::getBit(unsigned Bit) const {
738 if (getType() == BitRecTy::get())
739 return const_cast<OpInit*>(this);
740 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
743 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
744 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
745 static Pool<DenseMap<Key, UnOpInit *> > ThePool;
747 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
749 UnOpInit *&I = ThePool[TheKey];
750 if (!I) I = new UnOpInit(opc, lhs, Type);
754 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
755 switch (getOpcode()) {
757 if (getType()->getAsString() == "string") {
758 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
761 if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
762 return StringInit::get(LHSd->getDef()->getName());
764 if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
765 return StringInit::get(LHSi->getAsString());
767 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
768 std::string Name = LHSs->getValue();
770 // From TGParser::ParseIDValue
772 if (const RecordVal *RV = CurRec->getValue(Name)) {
773 if (RV->getType() != getType())
774 PrintFatalError("type mismatch in cast");
775 return VarInit::get(Name, RV->getType());
778 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
781 if (CurRec->isTemplateArg(TemplateArgName)) {
782 const RecordVal *RV = CurRec->getValue(TemplateArgName);
783 assert(RV && "Template arg doesn't exist??");
785 if (RV->getType() != getType())
786 PrintFatalError("type mismatch in cast");
788 return VarInit::get(TemplateArgName, RV->getType());
793 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
795 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
796 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
797 assert(RV && "Template arg doesn't exist??");
799 if (RV->getType() != getType())
800 PrintFatalError("type mismatch in cast");
802 return VarInit::get(MCName, RV->getType());
806 if (Record *D = (CurRec->getRecords()).getDef(Name))
807 return DefInit::get(D);
809 PrintFatalError(CurRec->getLoc(),
810 "Undefined reference:'" + Name + "'\n");
816 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
817 assert(LHSl->getSize() != 0 && "Empty list in car");
818 return LHSl->getElement(0);
823 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
824 assert(LHSl->getSize() != 0 && "Empty list in cdr");
825 // Note the +1. We can't just pass the result of getValues()
827 ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
828 ArrayRef<Init *>::iterator end = LHSl->getValues().end();
830 ListInit::get(ArrayRef<Init *>(begin, end - begin),
837 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
838 if (LHSl->getSize() == 0) {
839 return IntInit::get(1);
841 return IntInit::get(0);
844 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
845 if (LHSs->getValue().empty()) {
846 return IntInit::get(1);
848 return IntInit::get(0);
855 return const_cast<UnOpInit *>(this);
858 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
859 Init *lhs = LHS->resolveReferences(R, RV);
862 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, nullptr);
863 return Fold(&R, nullptr);
866 std::string UnOpInit::getAsString() const {
869 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
870 case HEAD: Result = "!head"; break;
871 case TAIL: Result = "!tail"; break;
872 case EMPTY: Result = "!empty"; break;
874 return Result + "(" + LHS->getAsString() + ")";
877 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
878 Init *rhs, RecTy *Type) {
880 std::pair<std::pair<unsigned, Init *>, Init *>,
884 static Pool<DenseMap<Key, BinOpInit *> > ThePool;
886 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
889 BinOpInit *&I = ThePool[TheKey];
890 if (!I) I = new BinOpInit(opc, lhs, rhs, Type);
894 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
895 switch (getOpcode()) {
897 DagInit *LHSs = dyn_cast<DagInit>(LHS);
898 DagInit *RHSs = dyn_cast<DagInit>(RHS);
900 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
901 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
902 if (!LOp || !ROp || LOp->getDef() != ROp->getDef())
903 PrintFatalError("Concated Dag operators do not match!");
904 std::vector<Init*> Args;
905 std::vector<std::string> ArgNames;
906 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
907 Args.push_back(LHSs->getArg(i));
908 ArgNames.push_back(LHSs->getArgName(i));
910 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
911 Args.push_back(RHSs->getArg(i));
912 ArgNames.push_back(RHSs->getArgName(i));
914 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
919 ListInit *LHSs = dyn_cast<ListInit>(LHS);
920 ListInit *RHSs = dyn_cast<ListInit>(RHS);
922 std::vector<Init *> Args;
923 Args.insert(Args.end(), LHSs->begin(), LHSs->end());
924 Args.insert(Args.end(), RHSs->begin(), RHSs->end());
925 return ListInit::get(
926 Args, static_cast<ListRecTy *>(LHSs->getType())->getElementType());
931 StringInit *LHSs = dyn_cast<StringInit>(LHS);
932 StringInit *RHSs = dyn_cast<StringInit>(RHS);
934 return StringInit::get(LHSs->getValue() + RHSs->getValue());
938 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
939 // to string objects.
941 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
943 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
946 return IntInit::get(L->getValue() == R->getValue());
948 StringInit *LHSs = dyn_cast<StringInit>(LHS);
949 StringInit *RHSs = dyn_cast<StringInit>(RHS);
951 // Make sure we've resolved
953 return IntInit::get(LHSs->getValue() == RHSs->getValue());
963 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
965 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
967 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
969 switch (getOpcode()) {
970 default: llvm_unreachable("Bad opcode!");
971 case ADD: Result = LHSv + RHSv; break;
972 case AND: Result = LHSv & RHSv; break;
973 case SHL: Result = LHSv << RHSv; break;
974 case SRA: Result = LHSv >> RHSv; break;
975 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
977 return IntInit::get(Result);
982 return const_cast<BinOpInit *>(this);
985 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
986 Init *lhs = LHS->resolveReferences(R, RV);
987 Init *rhs = RHS->resolveReferences(R, RV);
989 if (LHS != lhs || RHS != rhs)
990 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R,nullptr);
991 return Fold(&R, nullptr);
994 std::string BinOpInit::getAsString() const {
997 case CONCAT: Result = "!con"; break;
998 case ADD: Result = "!add"; break;
999 case AND: Result = "!and"; break;
1000 case SHL: Result = "!shl"; break;
1001 case SRA: Result = "!sra"; break;
1002 case SRL: Result = "!srl"; break;
1003 case EQ: Result = "!eq"; break;
1004 case LISTCONCAT: Result = "!listconcat"; break;
1005 case STRCONCAT: Result = "!strconcat"; break;
1007 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
1010 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs,
1011 Init *mhs, Init *rhs,
1015 std::pair<std::pair<unsigned, RecTy *>, Init *>,
1021 typedef DenseMap<Key, TernOpInit *> Pool;
1022 static Pool ThePool;
1024 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
1030 TernOpInit *&I = ThePool[TheKey];
1031 if (!I) I = new TernOpInit(opc, lhs, mhs, rhs, Type);
1035 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1036 Record *CurRec, MultiClass *CurMultiClass);
1038 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
1039 RecTy *Type, Record *CurRec,
1040 MultiClass *CurMultiClass) {
1041 std::vector<Init *> NewOperands;
1043 TypedInit *TArg = dyn_cast<TypedInit>(Arg);
1045 // If this is a dag, recurse
1046 if (TArg && TArg->getType()->getAsString() == "dag") {
1047 Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
1048 CurRec, CurMultiClass);
1052 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
1053 OpInit *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i));
1056 Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1057 Type, CurRec, CurMultiClass);
1059 NewOperands.push_back(Result);
1061 NewOperands.push_back(Arg);
1063 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1064 NewOperands.push_back(Arg);
1066 NewOperands.push_back(RHSo->getOperand(i));
1070 // Now run the operator and use its result as the new leaf
1071 const OpInit *NewOp = RHSo->clone(NewOperands);
1072 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
1073 return (NewVal != NewOp) ? NewVal : nullptr;
1076 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1077 Record *CurRec, MultiClass *CurMultiClass) {
1078 DagInit *MHSd = dyn_cast<DagInit>(MHS);
1079 ListInit *MHSl = dyn_cast<ListInit>(MHS);
1081 OpInit *RHSo = dyn_cast<OpInit>(RHS);
1084 PrintFatalError(CurRec->getLoc(), "!foreach requires an operator\n");
1087 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1090 PrintFatalError(CurRec->getLoc(), "!foreach requires typed variable\n");
1092 if ((MHSd && isa<DagRecTy>(Type)) || (MHSl && isa<ListRecTy>(Type))) {
1094 Init *Val = MHSd->getOperator();
1095 Init *Result = EvaluateOperation(RHSo, LHS, Val,
1096 Type, CurRec, CurMultiClass);
1101 std::vector<std::pair<Init *, std::string> > args;
1102 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1104 std::string ArgName;
1105 Arg = MHSd->getArg(i);
1106 ArgName = MHSd->getArgName(i);
1109 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1110 CurRec, CurMultiClass);
1115 // TODO: Process arg names
1116 args.push_back(std::make_pair(Arg, ArgName));
1119 return DagInit::get(Val, "", args);
1122 std::vector<Init *> NewOperands;
1123 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1125 for (std::vector<Init *>::iterator li = NewList.begin(),
1126 liend = NewList.end();
1130 NewOperands.clear();
1131 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1132 // First, replace the foreach variable with the list item
1133 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1134 NewOperands.push_back(Item);
1136 NewOperands.push_back(RHSo->getOperand(i));
1140 // Now run the operator and use its result as the new list item
1141 const OpInit *NewOp = RHSo->clone(NewOperands);
1142 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1143 if (NewItem != NewOp)
1146 return ListInit::get(NewList, MHSl->getType());
1152 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1153 switch (getOpcode()) {
1155 DefInit *LHSd = dyn_cast<DefInit>(LHS);
1156 VarInit *LHSv = dyn_cast<VarInit>(LHS);
1157 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1159 DefInit *MHSd = dyn_cast<DefInit>(MHS);
1160 VarInit *MHSv = dyn_cast<VarInit>(MHS);
1161 StringInit *MHSs = dyn_cast<StringInit>(MHS);
1163 DefInit *RHSd = dyn_cast<DefInit>(RHS);
1164 VarInit *RHSv = dyn_cast<VarInit>(RHS);
1165 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1167 if ((LHSd && MHSd && RHSd)
1168 || (LHSv && MHSv && RHSv)
1169 || (LHSs && MHSs && RHSs)) {
1171 Record *Val = RHSd->getDef();
1172 if (LHSd->getAsString() == RHSd->getAsString()) {
1173 Val = MHSd->getDef();
1175 return DefInit::get(Val);
1178 std::string Val = RHSv->getName();
1179 if (LHSv->getAsString() == RHSv->getAsString()) {
1180 Val = MHSv->getName();
1182 return VarInit::get(Val, getType());
1185 std::string Val = RHSs->getValue();
1187 std::string::size_type found;
1188 std::string::size_type idx = 0;
1190 found = Val.find(LHSs->getValue(), idx);
1191 if (found != std::string::npos) {
1192 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1194 idx = found + MHSs->getValue().size();
1195 } while (found != std::string::npos);
1197 return StringInit::get(Val);
1204 Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1205 CurRec, CurMultiClass);
1213 IntInit *LHSi = dyn_cast<IntInit>(LHS);
1214 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1215 LHSi = dyn_cast<IntInit>(I);
1217 if (LHSi->getValue()) {
1227 return const_cast<TernOpInit *>(this);
1230 Init *TernOpInit::resolveReferences(Record &R,
1231 const RecordVal *RV) const {
1232 Init *lhs = LHS->resolveReferences(R, RV);
1234 if (Opc == IF && lhs != LHS) {
1235 IntInit *Value = dyn_cast<IntInit>(lhs);
1236 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1237 Value = dyn_cast<IntInit>(I);
1240 if (Value->getValue()) {
1241 Init *mhs = MHS->resolveReferences(R, RV);
1242 return (TernOpInit::get(getOpcode(), lhs, mhs,
1243 RHS, getType()))->Fold(&R, nullptr);
1245 Init *rhs = RHS->resolveReferences(R, RV);
1246 return (TernOpInit::get(getOpcode(), lhs, MHS,
1247 rhs, getType()))->Fold(&R, nullptr);
1252 Init *mhs = MHS->resolveReferences(R, RV);
1253 Init *rhs = RHS->resolveReferences(R, RV);
1255 if (LHS != lhs || MHS != mhs || RHS != rhs)
1256 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1257 getType()))->Fold(&R, nullptr);
1258 return Fold(&R, nullptr);
1261 std::string TernOpInit::getAsString() const {
1264 case SUBST: Result = "!subst"; break;
1265 case FOREACH: Result = "!foreach"; break;
1266 case IF: Result = "!if"; break;
1268 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
1269 + RHS->getAsString() + ")";
1272 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1273 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
1274 if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
1275 return Field->getType();
1280 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1281 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1282 if (!T) return nullptr; // Cannot subscript a non-bits variable.
1283 unsigned NumBits = T->getNumBits();
1285 SmallVector<Init *, 16> NewBits(Bits.size());
1286 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1287 if (Bits[i] >= NumBits)
1290 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1292 return BitsInit::get(NewBits);
1296 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1297 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1298 if (!T) return nullptr; // Cannot subscript a non-list variable.
1300 if (Elements.size() == 1)
1301 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1303 std::vector<Init*> ListInits;
1304 ListInits.reserve(Elements.size());
1305 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1306 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1308 return ListInit::get(ListInits, T);
1312 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1313 Init *Value = StringInit::get(VN);
1314 return VarInit::get(Value, T);
1317 VarInit *VarInit::get(Init *VN, RecTy *T) {
1318 typedef std::pair<RecTy *, Init *> Key;
1319 static Pool<DenseMap<Key, VarInit *> > ThePool;
1321 Key TheKey(std::make_pair(T, VN));
1323 VarInit *&I = ThePool[TheKey];
1324 if (!I) I = new VarInit(VN, T);
1328 const std::string &VarInit::getName() const {
1329 StringInit *NameString = dyn_cast<StringInit>(getNameInit());
1330 assert(NameString && "VarInit name is not a string!");
1331 return NameString->getValue();
1334 Init *VarInit::getBit(unsigned Bit) const {
1335 if (getType() == BitRecTy::get())
1336 return const_cast<VarInit*>(this);
1337 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1340 Init *VarInit::resolveListElementReference(Record &R,
1341 const RecordVal *IRV,
1342 unsigned Elt) const {
1343 if (R.isTemplateArg(getNameInit())) return nullptr;
1344 if (IRV && IRV->getNameInit() != getNameInit()) return nullptr;
1346 RecordVal *RV = R.getValue(getNameInit());
1347 assert(RV && "Reference to a non-existent variable?");
1348 ListInit *LI = dyn_cast<ListInit>(RV->getValue());
1350 TypedInit *VI = dyn_cast<TypedInit>(RV->getValue());
1351 assert(VI && "Invalid list element!");
1352 return VarListElementInit::get(VI, Elt);
1355 if (Elt >= LI->getSize())
1356 return nullptr; // Out of range reference.
1357 Init *E = LI->getElement(Elt);
1358 // If the element is set to some value, or if we are resolving a reference
1359 // to a specific variable and that variable is explicitly unset, then
1360 // replace the VarListElementInit with it.
1361 if (IRV || !isa<UnsetInit>(E))
1367 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1368 if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
1369 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1370 return RV->getType();
1374 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1375 const std::string &FieldName) const {
1376 if (isa<RecordRecTy>(getType()))
1377 if (const RecordVal *Val = R.getValue(VarName)) {
1378 if (RV != Val && (RV || isa<UnsetInit>(Val->getValue())))
1380 Init *TheInit = Val->getValue();
1381 assert(TheInit != this && "Infinite loop detected!");
1382 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1390 /// resolveReferences - This method is used by classes that refer to other
1391 /// variables which may not be defined at the time the expression is formed.
1392 /// If a value is set for the variable later, this method will be called on
1393 /// users of the value to allow the value to propagate out.
1395 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1396 if (RecordVal *Val = R.getValue(VarName))
1397 if (RV == Val || (!RV && !isa<UnsetInit>(Val->getValue())))
1398 return Val->getValue();
1399 return const_cast<VarInit *>(this);
1402 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1403 typedef std::pair<TypedInit *, unsigned> Key;
1404 typedef DenseMap<Key, VarBitInit *> Pool;
1406 static Pool ThePool;
1408 Key TheKey(std::make_pair(T, B));
1410 VarBitInit *&I = ThePool[TheKey];
1411 if (!I) I = new VarBitInit(T, B);
1415 std::string VarBitInit::getAsString() const {
1416 return TI->getAsString() + "{" + utostr(Bit) + "}";
1419 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1420 Init *I = TI->resolveReferences(R, RV);
1422 return I->getBit(getBitNum());
1424 return const_cast<VarBitInit*>(this);
1427 VarListElementInit *VarListElementInit::get(TypedInit *T,
1429 typedef std::pair<TypedInit *, unsigned> Key;
1430 typedef DenseMap<Key, VarListElementInit *> Pool;
1432 static Pool ThePool;
1434 Key TheKey(std::make_pair(T, E));
1436 VarListElementInit *&I = ThePool[TheKey];
1437 if (!I) I = new VarListElementInit(T, E);
1441 std::string VarListElementInit::getAsString() const {
1442 return TI->getAsString() + "[" + utostr(Element) + "]";
1446 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1447 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1450 return const_cast<VarListElementInit *>(this);
1453 Init *VarListElementInit::getBit(unsigned Bit) const {
1454 if (getType() == BitRecTy::get())
1455 return const_cast<VarListElementInit*>(this);
1456 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1459 Init *VarListElementInit:: resolveListElementReference(Record &R,
1460 const RecordVal *RV,
1461 unsigned Elt) const {
1462 Init *Result = TI->resolveListElementReference(R, RV, Element);
1465 if (TypedInit *TInit = dyn_cast<TypedInit>(Result)) {
1466 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1467 if (Result2) return Result2;
1468 return new VarListElementInit(TInit, Elt);
1476 DefInit *DefInit::get(Record *R) {
1477 return R->getDefInit();
1480 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1481 if (const RecordVal *RV = Def->getValue(FieldName))
1482 return RV->getType();
1486 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1487 const std::string &FieldName) const {
1488 return Def->getValue(FieldName)->getValue();
1492 std::string DefInit::getAsString() const {
1493 return Def->getName();
1496 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1497 typedef std::pair<Init *, TableGenStringKey> Key;
1498 typedef DenseMap<Key, FieldInit *> Pool;
1499 static Pool ThePool;
1501 Key TheKey(std::make_pair(R, FN));
1503 FieldInit *&I = ThePool[TheKey];
1504 if (!I) I = new FieldInit(R, FN);
1508 Init *FieldInit::getBit(unsigned Bit) const {
1509 if (getType() == BitRecTy::get())
1510 return const_cast<FieldInit*>(this);
1511 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1514 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1515 unsigned Elt) const {
1516 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1517 if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
1518 if (Elt >= LI->getSize()) return nullptr;
1519 Init *E = LI->getElement(Elt);
1521 // If the element is set to some value, or if we are resolving a
1522 // reference to a specific variable and that variable is explicitly
1523 // unset, then replace the VarListElementInit with it.
1524 if (RV || !isa<UnsetInit>(E))
1530 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1531 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1533 Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1535 Init *BVR = BitsVal->resolveReferences(R, RV);
1536 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1539 if (NewRec != Rec) {
1540 return FieldInit::get(NewRec, FieldName);
1542 return const_cast<FieldInit *>(this);
1545 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, const std::string &VN,
1546 ArrayRef<Init *> ArgRange,
1547 ArrayRef<std::string> NameRange) {
1551 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1552 ArrayRef<std::string>::iterator Name = NameRange.begin();
1553 while (Arg != ArgRange.end()) {
1554 assert(Name != NameRange.end() && "Arg name underflow!");
1555 ID.AddPointer(*Arg++);
1556 ID.AddString(*Name++);
1558 assert(Name == NameRange.end() && "Arg name overflow!");
1562 DagInit::get(Init *V, const std::string &VN,
1563 ArrayRef<Init *> ArgRange,
1564 ArrayRef<std::string> NameRange) {
1565 typedef FoldingSet<DagInit> Pool;
1566 static Pool ThePool;
1568 FoldingSetNodeID ID;
1569 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1572 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1575 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1576 ThePool.InsertNode(I, IP);
1582 DagInit::get(Init *V, const std::string &VN,
1583 const std::vector<std::pair<Init*, std::string> > &args) {
1584 typedef std::pair<Init*, std::string> PairType;
1586 std::vector<Init *> Args;
1587 std::vector<std::string> Names;
1589 for (std::vector<PairType>::const_iterator i = args.begin(),
1593 Args.push_back(i->first);
1594 Names.push_back(i->second);
1597 return DagInit::get(V, VN, Args, Names);
1600 void DagInit::Profile(FoldingSetNodeID &ID) const {
1601 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1604 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1605 std::vector<Init*> NewArgs;
1606 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1607 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1609 Init *Op = Val->resolveReferences(R, RV);
1611 if (Args != NewArgs || Op != Val)
1612 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1614 return const_cast<DagInit *>(this);
1618 std::string DagInit::getAsString() const {
1619 std::string Result = "(" + Val->getAsString();
1620 if (!ValName.empty())
1621 Result += ":" + ValName;
1623 Result += " " + Args[0]->getAsString();
1624 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1625 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1626 Result += ", " + Args[i]->getAsString();
1627 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1630 return Result + ")";
1634 //===----------------------------------------------------------------------===//
1635 // Other implementations
1636 //===----------------------------------------------------------------------===//
1638 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1639 : Name(N), Ty(T), Prefix(P) {
1640 Value = Ty->convertValue(UnsetInit::get());
1641 assert(Value && "Cannot create unset value for current type!");
1644 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1645 : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1646 Value = Ty->convertValue(UnsetInit::get());
1647 assert(Value && "Cannot create unset value for current type!");
1650 const std::string &RecordVal::getName() const {
1651 StringInit *NameString = dyn_cast<StringInit>(Name);
1652 assert(NameString && "RecordVal name is not a string!");
1653 return NameString->getValue();
1656 void RecordVal::dump() const { errs() << *this; }
1658 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1659 if (getPrefix()) OS << "field ";
1660 OS << *getType() << " " << getNameInitAsString();
1663 OS << " = " << *getValue();
1665 if (PrintSem) OS << ";\n";
1668 unsigned Record::LastID = 0;
1670 void Record::init() {
1673 // Every record potentially has a def at the top. This value is
1674 // replaced with the top-level def name at instantiation time.
1675 RecordVal DN("NAME", StringRecTy::get(), 0);
1679 void Record::checkName() {
1680 // Ensure the record name has string type.
1681 const TypedInit *TypedName = dyn_cast<const TypedInit>(Name);
1682 assert(TypedName && "Record name is not typed!");
1683 RecTy *Type = TypedName->getType();
1684 if (!isa<StringRecTy>(Type))
1685 PrintFatalError(getLoc(), "Record name is not a string!");
1688 DefInit *Record::getDefInit() {
1690 TheInit = new DefInit(this, new RecordRecTy(this));
1694 const std::string &Record::getName() const {
1695 const StringInit *NameString = dyn_cast<StringInit>(Name);
1696 assert(NameString && "Record name is not a string!");
1697 return NameString->getValue();
1700 void Record::setName(Init *NewName) {
1701 if (TrackedRecords.getDef(Name->getAsUnquotedString()) == this) {
1702 TrackedRecords.removeDef(Name->getAsUnquotedString());
1703 TrackedRecords.addDef(this);
1704 } else if (TrackedRecords.getClass(Name->getAsUnquotedString()) == this) {
1705 TrackedRecords.removeClass(Name->getAsUnquotedString());
1706 TrackedRecords.addClass(this);
1707 } // Otherwise this isn't yet registered.
1710 // DO NOT resolve record values to the name at this point because
1711 // there might be default values for arguments of this def. Those
1712 // arguments might not have been resolved yet so we don't want to
1713 // prematurely assume values for those arguments were not passed to
1716 // Nonetheless, it may be that some of this Record's values
1717 // reference the record name. Indeed, the reason for having the
1718 // record name be an Init is to provide this flexibility. The extra
1719 // resolve steps after completely instantiating defs takes care of
1720 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1723 void Record::setName(const std::string &Name) {
1724 setName(StringInit::get(Name));
1727 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1728 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1730 void Record::resolveReferencesTo(const RecordVal *RV) {
1731 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1732 if (RV == &Values[i]) // Skip resolve the same field as the given one
1734 if (Init *V = Values[i].getValue())
1735 if (Values[i].setValue(V->resolveReferences(*this, RV)))
1736 PrintFatalError(getLoc(), "Invalid value is found when setting '"
1737 + Values[i].getNameInitAsString()
1738 + "' after resolving references"
1739 + (RV ? " against '" + RV->getNameInitAsString()
1741 + RV->getValue()->getAsUnquotedString() + ")"
1745 Init *OldName = getNameInit();
1746 Init *NewName = Name->resolveReferences(*this, RV);
1747 if (NewName != OldName) {
1748 // Re-register with RecordKeeper.
1753 void Record::dump() const { errs() << *this; }
1755 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1756 OS << R.getNameInitAsString();
1758 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1759 if (!TArgs.empty()) {
1761 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1763 const RecordVal *RV = R.getValue(TArgs[i]);
1764 assert(RV && "Template argument record not found??");
1765 RV->print(OS, false);
1771 const std::vector<Record*> &SC = R.getSuperClasses();
1774 for (unsigned i = 0, e = SC.size(); i != e; ++i)
1775 OS << " " << SC[i]->getNameInitAsString();
1779 const std::vector<RecordVal> &Vals = R.getValues();
1780 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1781 if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1783 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1784 if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1790 /// getValueInit - Return the initializer for a value with the specified name,
1791 /// or abort if the field does not exist.
1793 Init *Record::getValueInit(StringRef FieldName) const {
1794 const RecordVal *R = getValue(FieldName);
1795 if (!R || !R->getValue())
1796 PrintFatalError(getLoc(), "Record `" + getName() +
1797 "' does not have a field named `" + FieldName + "'!\n");
1798 return R->getValue();
1802 /// getValueAsString - This method looks up the specified field and returns its
1803 /// value as a string, aborts if the field does not exist or if
1804 /// the value is not a string.
1806 std::string Record::getValueAsString(StringRef FieldName) const {
1807 const RecordVal *R = getValue(FieldName);
1808 if (!R || !R->getValue())
1809 PrintFatalError(getLoc(), "Record `" + getName() +
1810 "' does not have a field named `" + FieldName + "'!\n");
1812 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1813 return SI->getValue();
1814 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1815 FieldName + "' does not have a string initializer!");
1818 /// getValueAsBitsInit - This method looks up the specified field and returns
1819 /// its value as a BitsInit, aborts if the field does not exist or if
1820 /// the value is not the right type.
1822 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1823 const RecordVal *R = getValue(FieldName);
1824 if (!R || !R->getValue())
1825 PrintFatalError(getLoc(), "Record `" + getName() +
1826 "' does not have a field named `" + FieldName + "'!\n");
1828 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
1830 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1831 FieldName + "' does not have a BitsInit initializer!");
1834 /// getValueAsListInit - This method looks up the specified field and returns
1835 /// its value as a ListInit, aborting if the field does not exist or if
1836 /// the value is not the right type.
1838 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1839 const RecordVal *R = getValue(FieldName);
1840 if (!R || !R->getValue())
1841 PrintFatalError(getLoc(), "Record `" + getName() +
1842 "' does not have a field named `" + FieldName + "'!\n");
1844 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
1846 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1847 FieldName + "' does not have a list initializer!");
1850 /// getValueAsListOfDefs - This method looks up the specified field and returns
1851 /// its value as a vector of records, aborting if the field does not exist
1852 /// or if the value is not the right type.
1854 std::vector<Record*>
1855 Record::getValueAsListOfDefs(StringRef FieldName) const {
1856 ListInit *List = getValueAsListInit(FieldName);
1857 std::vector<Record*> Defs;
1858 for (unsigned i = 0; i < List->getSize(); i++) {
1859 if (DefInit *DI = dyn_cast<DefInit>(List->getElement(i))) {
1860 Defs.push_back(DI->getDef());
1862 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1863 FieldName + "' list is not entirely DefInit!");
1869 /// getValueAsInt - This method looks up the specified field and returns its
1870 /// value as an int64_t, aborting if the field does not exist or if the value
1871 /// is not the right type.
1873 int64_t Record::getValueAsInt(StringRef FieldName) const {
1874 const RecordVal *R = getValue(FieldName);
1875 if (!R || !R->getValue())
1876 PrintFatalError(getLoc(), "Record `" + getName() +
1877 "' does not have a field named `" + FieldName + "'!\n");
1879 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
1880 return II->getValue();
1881 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1882 FieldName + "' does not have an int initializer!");
1885 /// getValueAsListOfInts - This method looks up the specified field and returns
1886 /// its value as a vector of integers, aborting if the field does not exist or
1887 /// if the value is not the right type.
1889 std::vector<int64_t>
1890 Record::getValueAsListOfInts(StringRef FieldName) const {
1891 ListInit *List = getValueAsListInit(FieldName);
1892 std::vector<int64_t> Ints;
1893 for (unsigned i = 0; i < List->getSize(); i++) {
1894 if (IntInit *II = dyn_cast<IntInit>(List->getElement(i))) {
1895 Ints.push_back(II->getValue());
1897 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1898 FieldName + "' does not have a list of ints initializer!");
1904 /// getValueAsListOfStrings - This method looks up the specified field and
1905 /// returns its value as a vector of strings, aborting if the field does not
1906 /// exist or if the value is not the right type.
1908 std::vector<std::string>
1909 Record::getValueAsListOfStrings(StringRef FieldName) const {
1910 ListInit *List = getValueAsListInit(FieldName);
1911 std::vector<std::string> Strings;
1912 for (unsigned i = 0; i < List->getSize(); i++) {
1913 if (StringInit *II = dyn_cast<StringInit>(List->getElement(i))) {
1914 Strings.push_back(II->getValue());
1916 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1917 FieldName + "' does not have a list of strings initializer!");
1923 /// getValueAsDef - This method looks up the specified field and returns its
1924 /// value as a Record, aborting if the field does not exist or if the value
1925 /// is not the right type.
1927 Record *Record::getValueAsDef(StringRef FieldName) const {
1928 const RecordVal *R = getValue(FieldName);
1929 if (!R || !R->getValue())
1930 PrintFatalError(getLoc(), "Record `" + getName() +
1931 "' does not have a field named `" + FieldName + "'!\n");
1933 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
1934 return DI->getDef();
1935 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1936 FieldName + "' does not have a def initializer!");
1939 /// getValueAsBit - This method looks up the specified field and returns its
1940 /// value as a bit, aborting if the field does not exist or if the value is
1941 /// not the right type.
1943 bool Record::getValueAsBit(StringRef FieldName) const {
1944 const RecordVal *R = getValue(FieldName);
1945 if (!R || !R->getValue())
1946 PrintFatalError(getLoc(), "Record `" + getName() +
1947 "' does not have a field named `" + FieldName + "'!\n");
1949 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1950 return BI->getValue();
1951 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1952 FieldName + "' does not have a bit initializer!");
1955 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1956 const RecordVal *R = getValue(FieldName);
1957 if (!R || !R->getValue())
1958 PrintFatalError(getLoc(), "Record `" + getName() +
1959 "' does not have a field named `" + FieldName.str() + "'!\n");
1961 if (R->getValue() == UnsetInit::get()) {
1966 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1967 return BI->getValue();
1968 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1969 FieldName + "' does not have a bit initializer!");
1972 /// getValueAsDag - This method looks up the specified field and returns its
1973 /// value as an Dag, aborting if the field does not exist or if the value is
1974 /// not the right type.
1976 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1977 const RecordVal *R = getValue(FieldName);
1978 if (!R || !R->getValue())
1979 PrintFatalError(getLoc(), "Record `" + getName() +
1980 "' does not have a field named `" + FieldName + "'!\n");
1982 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
1984 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1985 FieldName + "' does not have a dag initializer!");
1989 void MultiClass::dump() const {
1990 errs() << "Record:\n";
1993 errs() << "Defs:\n";
1994 for (RecordVector::const_iterator r = DefPrototypes.begin(),
1995 rend = DefPrototypes.end();
2003 void RecordKeeper::dump() const { errs() << *this; }
2005 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
2006 OS << "------------- Classes -----------------\n";
2007 const std::map<std::string, Record*> &Classes = RK.getClasses();
2008 for (std::map<std::string, Record*>::const_iterator I = Classes.begin(),
2009 E = Classes.end(); I != E; ++I)
2010 OS << "class " << *I->second;
2012 OS << "------------- Defs -----------------\n";
2013 const std::map<std::string, Record*> &Defs = RK.getDefs();
2014 for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),
2015 E = Defs.end(); I != E; ++I)
2016 OS << "def " << *I->second;
2021 /// getAllDerivedDefinitions - This method returns all concrete definitions
2022 /// that derive from the specified class name. If a class with the specified
2023 /// name does not exist, an error is printed and true is returned.
2024 std::vector<Record*>
2025 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
2026 Record *Class = getClass(ClassName);
2028 PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
2030 std::vector<Record*> Defs;
2031 for (std::map<std::string, Record*>::const_iterator I = getDefs().begin(),
2032 E = getDefs().end(); I != E; ++I)
2033 if (I->second->isSubClassOf(Class))
2034 Defs.push_back(I->second);
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);