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/TableGen/Error.h"
16 #include "llvm/Support/DataTypes.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/Format.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/Hashing.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringMap.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 Init *BitRecTy::convertValue(BitsInit *BI) {
99 if (BI->getNumBits() != 1) return 0; // Only accept if just one bit!
100 return BI->getBit(0);
103 bool BitRecTy::baseClassOf(const BitsRecTy *RHS) const {
104 return RHS->getNumBits() == 1;
107 Init *BitRecTy::convertValue(IntInit *II) {
108 int64_t Val = II->getValue();
109 if (Val != 0 && Val != 1) return 0; // Only accept 0 or 1 for a bit!
111 return BitInit::get(Val != 0);
114 Init *BitRecTy::convertValue(TypedInit *VI) {
115 RecTy *Ty = VI->getType();
116 if (dyn_cast<BitRecTy>(Ty) ||
117 dyn_cast<BitsRecTy>(Ty) ||
118 dyn_cast<IntRecTy>(Ty))
119 return VI; // Accept variable if it is already of bit type!
123 BitsRecTy *BitsRecTy::get(unsigned Sz) {
124 static std::vector<BitsRecTy*> Shared;
125 if (Sz >= Shared.size())
126 Shared.resize(Sz + 1);
127 BitsRecTy *&Ty = Shared[Sz];
129 Ty = new BitsRecTy(Sz);
133 std::string BitsRecTy::getAsString() const {
134 return "bits<" + utostr(Size) + ">";
137 Init *BitsRecTy::convertValue(UnsetInit *UI) {
138 SmallVector<Init *, 16> NewBits(Size);
140 for (unsigned i = 0; i != Size; ++i)
141 NewBits[i] = UnsetInit::get();
143 return BitsInit::get(NewBits);
146 Init *BitsRecTy::convertValue(BitInit *UI) {
147 if (Size != 1) return 0; // Can only convert single bit.
148 return BitsInit::get(UI);
151 /// canFitInBitfield - Return true if the number of bits is large enough to hold
152 /// the integer value.
153 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
154 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
155 return (NumBits >= sizeof(Value) * 8) ||
156 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
159 /// convertValue from Int initializer to bits type: Split the integer up into the
160 /// appropriate bits.
162 Init *BitsRecTy::convertValue(IntInit *II) {
163 int64_t Value = II->getValue();
164 // Make sure this bitfield is large enough to hold the integer value.
165 if (!canFitInBitfield(Value, Size))
168 SmallVector<Init *, 16> NewBits(Size);
170 for (unsigned i = 0; i != Size; ++i)
171 NewBits[i] = BitInit::get(Value & (1LL << i));
173 return BitsInit::get(NewBits);
176 Init *BitsRecTy::convertValue(BitsInit *BI) {
177 // If the number of bits is right, return it. Otherwise we need to expand or
179 if (BI->getNumBits() == Size) return BI;
183 Init *BitsRecTy::convertValue(TypedInit *VI) {
184 if (Size == 1 && dyn_cast<BitRecTy>(VI->getType()))
185 return BitsInit::get(VI);
187 if (VI->getType()->typeIsConvertibleTo(this)) {
188 SmallVector<Init *, 16> NewBits(Size);
190 for (unsigned i = 0; i != Size; ++i)
191 NewBits[i] = VarBitInit::get(VI, i);
192 return BitsInit::get(NewBits);
198 Init *IntRecTy::convertValue(BitInit *BI) {
199 return IntInit::get(BI->getValue());
202 Init *IntRecTy::convertValue(BitsInit *BI) {
204 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
205 if (BitInit *Bit = dynamic_cast<BitInit*>(BI->getBit(i))) {
206 Result |= Bit->getValue() << i;
210 return IntInit::get(Result);
213 Init *IntRecTy::convertValue(TypedInit *TI) {
214 if (TI->getType()->typeIsConvertibleTo(this))
215 return TI; // Accept variable if already of the right type!
219 Init *StringRecTy::convertValue(UnOpInit *BO) {
220 if (BO->getOpcode() == UnOpInit::CAST) {
221 Init *L = BO->getOperand()->convertInitializerTo(this);
222 if (L == 0) return 0;
223 if (L != BO->getOperand())
224 return UnOpInit::get(UnOpInit::CAST, L, new StringRecTy);
228 return convertValue((TypedInit*)BO);
231 Init *StringRecTy::convertValue(BinOpInit *BO) {
232 if (BO->getOpcode() == BinOpInit::STRCONCAT) {
233 Init *L = BO->getLHS()->convertInitializerTo(this);
234 Init *R = BO->getRHS()->convertInitializerTo(this);
235 if (L == 0 || R == 0) return 0;
236 if (L != BO->getLHS() || R != BO->getRHS())
237 return BinOpInit::get(BinOpInit::STRCONCAT, L, R, new StringRecTy);
241 return convertValue((TypedInit*)BO);
245 Init *StringRecTy::convertValue(TypedInit *TI) {
246 if (dyn_cast<StringRecTy>(TI->getType()))
247 return TI; // Accept variable if already of the right type!
251 std::string ListRecTy::getAsString() const {
252 return "list<" + Ty->getAsString() + ">";
255 Init *ListRecTy::convertValue(ListInit *LI) {
256 std::vector<Init*> Elements;
258 // Verify that all of the elements of the list are subclasses of the
259 // appropriate class!
260 for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
261 if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
262 Elements.push_back(CI);
266 ListRecTy *LType = dyn_cast<ListRecTy>(LI->getType());
271 return ListInit::get(Elements, this);
274 Init *ListRecTy::convertValue(TypedInit *TI) {
275 // Ensure that TI is compatible with our class.
276 if (ListRecTy *LRT = dyn_cast<ListRecTy>(TI->getType()))
277 if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
282 Init *DagRecTy::convertValue(TypedInit *TI) {
283 if (TI->getType()->typeIsConvertibleTo(this))
288 Init *DagRecTy::convertValue(UnOpInit *BO) {
289 if (BO->getOpcode() == UnOpInit::CAST) {
290 Init *L = BO->getOperand()->convertInitializerTo(this);
291 if (L == 0) return 0;
292 if (L != BO->getOperand())
293 return UnOpInit::get(UnOpInit::CAST, L, new DagRecTy);
299 Init *DagRecTy::convertValue(BinOpInit *BO) {
300 if (BO->getOpcode() == BinOpInit::CONCAT) {
301 Init *L = BO->getLHS()->convertInitializerTo(this);
302 Init *R = BO->getRHS()->convertInitializerTo(this);
303 if (L == 0 || R == 0) return 0;
304 if (L != BO->getLHS() || R != BO->getRHS())
305 return BinOpInit::get(BinOpInit::CONCAT, L, R, new DagRecTy);
311 RecordRecTy *RecordRecTy::get(Record *R) {
312 return dyn_cast<RecordRecTy>(R->getDefInit()->getType());
315 std::string RecordRecTy::getAsString() const {
316 return Rec->getName();
319 Init *RecordRecTy::convertValue(DefInit *DI) {
320 // Ensure that DI is a subclass of Rec.
321 if (!DI->getDef()->isSubClassOf(Rec))
326 Init *RecordRecTy::convertValue(TypedInit *TI) {
327 // Ensure that TI is compatible with Rec.
328 if (RecordRecTy *RRT = dyn_cast<RecordRecTy>(TI->getType()))
329 if (RRT->getRecord()->isSubClassOf(getRecord()) ||
330 RRT->getRecord() == getRecord())
335 bool RecordRecTy::baseClassOf(const RecordRecTy *RHS) const {
336 if (Rec == RHS->getRecord() || RHS->getRecord()->isSubClassOf(Rec))
339 const std::vector<Record*> &SC = Rec->getSuperClasses();
340 for (unsigned i = 0, e = SC.size(); i != e; ++i)
341 if (RHS->getRecord()->isSubClassOf(SC[i]))
347 /// resolveTypes - Find a common type that T1 and T2 convert to.
348 /// Return 0 if no such type exists.
350 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
351 if (T1->typeIsConvertibleTo(T2))
353 if (T2->typeIsConvertibleTo(T1))
356 // If one is a Record type, check superclasses
357 if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
358 // See if T2 inherits from a type T1 also inherits from
359 const std::vector<Record *> &T1SuperClasses =
360 RecTy1->getRecord()->getSuperClasses();
361 for(std::vector<Record *>::const_iterator i = T1SuperClasses.begin(),
362 iend = T1SuperClasses.end();
365 RecordRecTy *SuperRecTy1 = RecordRecTy::get(*i);
366 RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
368 if (NewType1 != SuperRecTy1) {
375 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) {
376 // See if T1 inherits from a type T2 also inherits from
377 const std::vector<Record *> &T2SuperClasses =
378 RecTy2->getRecord()->getSuperClasses();
379 for (std::vector<Record *>::const_iterator i = T2SuperClasses.begin(),
380 iend = T2SuperClasses.end();
383 RecordRecTy *SuperRecTy2 = RecordRecTy::get(*i);
384 RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
386 if (NewType2 != SuperRecTy2) {
397 //===----------------------------------------------------------------------===//
398 // Initializer implementations
399 //===----------------------------------------------------------------------===//
401 void Init::anchor() { }
402 void Init::dump() const { return print(errs()); }
404 void UnsetInit::anchor() { }
406 UnsetInit *UnsetInit::get() {
407 static UnsetInit TheInit;
411 void BitInit::anchor() { }
413 BitInit *BitInit::get(bool V) {
414 static BitInit True(true);
415 static BitInit False(false);
417 return V ? &True : &False;
421 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
422 ID.AddInteger(Range.size());
424 for (ArrayRef<Init *>::iterator i = Range.begin(),
431 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
432 typedef FoldingSet<BitsInit> Pool;
436 ProfileBitsInit(ID, Range);
439 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
442 BitsInit *I = new BitsInit(Range);
443 ThePool.InsertNode(I, IP);
448 void BitsInit::Profile(FoldingSetNodeID &ID) const {
449 ProfileBitsInit(ID, Bits);
453 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
454 SmallVector<Init *, 16> NewBits(Bits.size());
456 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
457 if (Bits[i] >= getNumBits())
459 NewBits[i] = getBit(Bits[i]);
461 return BitsInit::get(NewBits);
464 std::string BitsInit::getAsString() const {
465 std::string Result = "{ ";
466 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
467 if (i) Result += ", ";
468 if (Init *Bit = getBit(e-i-1))
469 Result += Bit->getAsString();
473 return Result + " }";
476 // Fix bit initializer to preserve the behavior that bit reference from a unset
477 // bits initializer will resolve into VarBitInit to keep the field name and bit
478 // number used in targets with fixed insn length.
479 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
480 if (RV || After != UnsetInit::get())
485 // resolveReferences - If there are any field references that refer to fields
486 // that have been filled in, we can propagate the values now.
488 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
489 bool Changed = false;
490 SmallVector<Init *, 16> NewBits(getNumBits());
492 Init *CachedInit = 0;
493 Init *CachedBitVar = 0;
494 bool CachedBitVarChanged = false;
496 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
497 Init *CurBit = Bits[i];
498 Init *CurBitVar = CurBit->getBitVar();
502 if (CurBitVar == CachedBitVar) {
503 if (CachedBitVarChanged) {
504 Init *Bit = CachedInit->getBit(CurBit->getBitNum());
505 NewBits[i] = fixBitInit(RV, CurBit, Bit);
509 CachedBitVar = CurBitVar;
510 CachedBitVarChanged = false;
515 CurBitVar = CurBitVar->resolveReferences(R, RV);
516 CachedBitVarChanged |= B != CurBitVar;
517 Changed |= B != CurBitVar;
518 } while (B != CurBitVar);
519 CachedInit = CurBitVar;
521 if (CachedBitVarChanged) {
522 Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
523 NewBits[i] = fixBitInit(RV, CurBit, Bit);
528 return BitsInit::get(NewBits);
530 return const_cast<BitsInit *>(this);
533 IntInit *IntInit::get(int64_t V) {
534 typedef DenseMap<int64_t, IntInit *> Pool;
537 IntInit *&I = ThePool[V];
538 if (!I) I = new IntInit(V);
542 std::string IntInit::getAsString() const {
543 return itostr(Value);
547 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
548 SmallVector<Init *, 16> NewBits(Bits.size());
550 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
554 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
556 return BitsInit::get(NewBits);
559 void StringInit::anchor() { }
561 StringInit *StringInit::get(StringRef V) {
562 typedef StringMap<StringInit *> Pool;
565 StringInit *&I = ThePool[V];
566 if (!I) I = new StringInit(V);
570 static void ProfileListInit(FoldingSetNodeID &ID,
571 ArrayRef<Init *> Range,
573 ID.AddInteger(Range.size());
574 ID.AddPointer(EltTy);
576 for (ArrayRef<Init *>::iterator i = Range.begin(),
583 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
584 typedef FoldingSet<ListInit> Pool;
587 // Just use the FoldingSetNodeID to compute a hash. Use a DenseMap
588 // for actual storage.
590 ProfileListInit(ID, Range, EltTy);
593 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
596 ListInit *I = new ListInit(Range, EltTy);
597 ThePool.InsertNode(I, IP);
601 void ListInit::Profile(FoldingSetNodeID &ID) const {
602 ListRecTy *ListType = dyn_cast<ListRecTy>(getType());
603 assert(ListType && "Bad type for ListInit!");
604 RecTy *EltTy = ListType->getElementType();
606 ProfileListInit(ID, Values, EltTy);
610 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
611 std::vector<Init*> Vals;
612 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
613 if (Elements[i] >= getSize())
615 Vals.push_back(getElement(Elements[i]));
617 return ListInit::get(Vals, getType());
620 Record *ListInit::getElementAsRecord(unsigned i) const {
621 assert(i < Values.size() && "List element index out of range!");
622 DefInit *DI = dynamic_cast<DefInit*>(Values[i]);
623 if (DI == 0) throw "Expected record in list!";
627 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
628 std::vector<Init*> Resolved;
629 Resolved.reserve(getSize());
630 bool Changed = false;
632 for (unsigned i = 0, e = getSize(); i != e; ++i) {
634 Init *CurElt = getElement(i);
638 CurElt = CurElt->resolveReferences(R, RV);
639 Changed |= E != CurElt;
640 } while (E != CurElt);
641 Resolved.push_back(E);
645 return ListInit::get(Resolved, getType());
646 return const_cast<ListInit *>(this);
649 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
650 unsigned Elt) const {
651 if (Elt >= getSize())
652 return 0; // Out of range reference.
653 Init *E = getElement(Elt);
654 // If the element is set to some value, or if we are resolving a reference
655 // to a specific variable and that variable is explicitly unset, then
656 // replace the VarListElementInit with it.
657 if (IRV || !dynamic_cast<UnsetInit*>(E))
662 std::string ListInit::getAsString() const {
663 std::string Result = "[";
664 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
665 if (i) Result += ", ";
666 Result += Values[i]->getAsString();
671 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
672 unsigned Elt) const {
673 Init *Resolved = resolveReferences(R, IRV);
674 OpInit *OResolved = dynamic_cast<OpInit *>(Resolved);
676 Resolved = OResolved->Fold(&R, 0);
679 if (Resolved != this) {
680 TypedInit *Typed = dynamic_cast<TypedInit *>(Resolved);
681 assert(Typed && "Expected typed init for list reference");
683 Init *New = Typed->resolveListElementReference(R, IRV, Elt);
686 return VarListElementInit::get(Typed, Elt);
693 Init *OpInit::getBit(unsigned Bit) const {
694 if (getType() == BitRecTy::get())
695 return const_cast<OpInit*>(this);
696 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
699 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
700 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
702 typedef DenseMap<Key, UnOpInit *> Pool;
705 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
707 UnOpInit *&I = ThePool[TheKey];
708 if (!I) I = new UnOpInit(opc, lhs, Type);
712 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
713 switch (getOpcode()) {
715 if (getType()->getAsString() == "string") {
716 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
721 DefInit *LHSd = dynamic_cast<DefInit*>(LHS);
723 return StringInit::get(LHSd->getDef()->getName());
726 IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
728 return StringInit::get(LHSi->getAsString());
731 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
733 std::string Name = LHSs->getValue();
735 // From TGParser::ParseIDValue
737 if (const RecordVal *RV = CurRec->getValue(Name)) {
738 if (RV->getType() != getType())
739 throw "type mismatch in cast";
740 return VarInit::get(Name, RV->getType());
743 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
746 if (CurRec->isTemplateArg(TemplateArgName)) {
747 const RecordVal *RV = CurRec->getValue(TemplateArgName);
748 assert(RV && "Template arg doesn't exist??");
750 if (RV->getType() != getType())
751 throw "type mismatch in cast";
753 return VarInit::get(TemplateArgName, RV->getType());
758 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
760 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
761 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
762 assert(RV && "Template arg doesn't exist??");
764 if (RV->getType() != getType())
765 throw "type mismatch in cast";
767 return VarInit::get(MCName, RV->getType());
771 if (Record *D = (CurRec->getRecords()).getDef(Name))
772 return DefInit::get(D);
774 throw TGError(CurRec->getLoc(), "Undefined reference:'" + Name + "'\n");
780 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
782 if (LHSl->getSize() == 0) {
783 assert(0 && "Empty list in car");
786 return LHSl->getElement(0);
791 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
793 if (LHSl->getSize() == 0) {
794 assert(0 && "Empty list in cdr");
797 // Note the +1. We can't just pass the result of getValues()
799 ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
800 ArrayRef<Init *>::iterator end = LHSl->getValues().end();
802 ListInit::get(ArrayRef<Init *>(begin, end - begin),
809 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
811 if (LHSl->getSize() == 0) {
812 return IntInit::get(1);
814 return IntInit::get(0);
817 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
819 if (LHSs->getValue().empty()) {
820 return IntInit::get(1);
822 return IntInit::get(0);
829 return const_cast<UnOpInit *>(this);
832 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
833 Init *lhs = LHS->resolveReferences(R, RV);
836 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, 0);
840 std::string UnOpInit::getAsString() const {
843 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
844 case HEAD: Result = "!head"; break;
845 case TAIL: Result = "!tail"; break;
846 case EMPTY: Result = "!empty"; break;
848 return Result + "(" + LHS->getAsString() + ")";
851 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
852 Init *rhs, RecTy *Type) {
854 std::pair<std::pair<unsigned, Init *>, Init *>,
858 typedef DenseMap<Key, BinOpInit *> Pool;
861 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
864 BinOpInit *&I = ThePool[TheKey];
865 if (!I) I = new BinOpInit(opc, lhs, rhs, Type);
869 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
870 switch (getOpcode()) {
872 DagInit *LHSs = dynamic_cast<DagInit*>(LHS);
873 DagInit *RHSs = dynamic_cast<DagInit*>(RHS);
875 DefInit *LOp = dynamic_cast<DefInit*>(LHSs->getOperator());
876 DefInit *ROp = dynamic_cast<DefInit*>(RHSs->getOperator());
877 if (LOp == 0 || ROp == 0 || LOp->getDef() != ROp->getDef())
878 throw "Concated Dag operators do not match!";
879 std::vector<Init*> Args;
880 std::vector<std::string> ArgNames;
881 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
882 Args.push_back(LHSs->getArg(i));
883 ArgNames.push_back(LHSs->getArgName(i));
885 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
886 Args.push_back(RHSs->getArg(i));
887 ArgNames.push_back(RHSs->getArgName(i));
889 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
894 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
895 StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
897 return StringInit::get(LHSs->getValue() + RHSs->getValue());
901 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
902 // to string objects.
904 dynamic_cast<IntInit*>(LHS->convertInitializerTo(IntRecTy::get()));
906 dynamic_cast<IntInit*>(RHS->convertInitializerTo(IntRecTy::get()));
909 return IntInit::get(L->getValue() == R->getValue());
911 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
912 StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
914 // Make sure we've resolved
916 return IntInit::get(LHSs->getValue() == RHSs->getValue());
923 IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
924 IntInit *RHSi = dynamic_cast<IntInit*>(RHS);
926 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
928 switch (getOpcode()) {
929 default: llvm_unreachable("Bad opcode!");
930 case SHL: Result = LHSv << RHSv; break;
931 case SRA: Result = LHSv >> RHSv; break;
932 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
934 return IntInit::get(Result);
939 return const_cast<BinOpInit *>(this);
942 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
943 Init *lhs = LHS->resolveReferences(R, RV);
944 Init *rhs = RHS->resolveReferences(R, RV);
946 if (LHS != lhs || RHS != rhs)
947 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R, 0);
951 std::string BinOpInit::getAsString() const {
954 case CONCAT: Result = "!con"; break;
955 case SHL: Result = "!shl"; break;
956 case SRA: Result = "!sra"; break;
957 case SRL: Result = "!srl"; break;
958 case EQ: Result = "!eq"; break;
959 case STRCONCAT: Result = "!strconcat"; break;
961 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
964 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs,
965 Init *mhs, Init *rhs,
969 std::pair<std::pair<unsigned, RecTy *>, Init *>,
975 typedef DenseMap<Key, TernOpInit *> Pool;
978 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
984 TernOpInit *&I = ThePool[TheKey];
985 if (!I) I = new TernOpInit(opc, lhs, mhs, rhs, Type);
989 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
990 Record *CurRec, MultiClass *CurMultiClass);
992 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
993 RecTy *Type, Record *CurRec,
994 MultiClass *CurMultiClass) {
995 std::vector<Init *> NewOperands;
997 TypedInit *TArg = dynamic_cast<TypedInit*>(Arg);
999 // If this is a dag, recurse
1000 if (TArg && TArg->getType()->getAsString() == "dag") {
1001 Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
1002 CurRec, CurMultiClass);
1010 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
1011 OpInit *RHSoo = dynamic_cast<OpInit*>(RHSo->getOperand(i));
1014 Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1015 Type, CurRec, CurMultiClass);
1017 NewOperands.push_back(Result);
1019 NewOperands.push_back(Arg);
1021 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1022 NewOperands.push_back(Arg);
1024 NewOperands.push_back(RHSo->getOperand(i));
1028 // Now run the operator and use its result as the new leaf
1029 const OpInit *NewOp = RHSo->clone(NewOperands);
1030 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
1031 if (NewVal != NewOp)
1037 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1038 Record *CurRec, MultiClass *CurMultiClass) {
1039 DagInit *MHSd = dynamic_cast<DagInit*>(MHS);
1040 ListInit *MHSl = dynamic_cast<ListInit*>(MHS);
1042 DagRecTy *DagType = dyn_cast<DagRecTy>(Type);
1043 ListRecTy *ListType = dyn_cast<ListRecTy>(Type);
1045 OpInit *RHSo = dynamic_cast<OpInit*>(RHS);
1048 throw TGError(CurRec->getLoc(), "!foreach requires an operator\n");
1051 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
1054 throw TGError(CurRec->getLoc(), "!foreach requires typed variable\n");
1057 if ((MHSd && DagType) || (MHSl && ListType)) {
1059 Init *Val = MHSd->getOperator();
1060 Init *Result = EvaluateOperation(RHSo, LHS, Val,
1061 Type, CurRec, CurMultiClass);
1066 std::vector<std::pair<Init *, std::string> > args;
1067 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1069 std::string ArgName;
1070 Arg = MHSd->getArg(i);
1071 ArgName = MHSd->getArgName(i);
1074 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1075 CurRec, CurMultiClass);
1080 // TODO: Process arg names
1081 args.push_back(std::make_pair(Arg, ArgName));
1084 return DagInit::get(Val, "", args);
1087 std::vector<Init *> NewOperands;
1088 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1090 for (std::vector<Init *>::iterator li = NewList.begin(),
1091 liend = NewList.end();
1095 NewOperands.clear();
1096 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1097 // First, replace the foreach variable with the list item
1098 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1099 NewOperands.push_back(Item);
1101 NewOperands.push_back(RHSo->getOperand(i));
1105 // Now run the operator and use its result as the new list item
1106 const OpInit *NewOp = RHSo->clone(NewOperands);
1107 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1108 if (NewItem != NewOp)
1111 return ListInit::get(NewList, MHSl->getType());
1117 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1118 switch (getOpcode()) {
1120 DefInit *LHSd = dynamic_cast<DefInit*>(LHS);
1121 VarInit *LHSv = dynamic_cast<VarInit*>(LHS);
1122 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
1124 DefInit *MHSd = dynamic_cast<DefInit*>(MHS);
1125 VarInit *MHSv = dynamic_cast<VarInit*>(MHS);
1126 StringInit *MHSs = dynamic_cast<StringInit*>(MHS);
1128 DefInit *RHSd = dynamic_cast<DefInit*>(RHS);
1129 VarInit *RHSv = dynamic_cast<VarInit*>(RHS);
1130 StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
1132 if ((LHSd && MHSd && RHSd)
1133 || (LHSv && MHSv && RHSv)
1134 || (LHSs && MHSs && RHSs)) {
1136 Record *Val = RHSd->getDef();
1137 if (LHSd->getAsString() == RHSd->getAsString()) {
1138 Val = MHSd->getDef();
1140 return DefInit::get(Val);
1143 std::string Val = RHSv->getName();
1144 if (LHSv->getAsString() == RHSv->getAsString()) {
1145 Val = MHSv->getName();
1147 return VarInit::get(Val, getType());
1150 std::string Val = RHSs->getValue();
1152 std::string::size_type found;
1153 std::string::size_type idx = 0;
1155 found = Val.find(LHSs->getValue(), idx);
1156 if (found != std::string::npos) {
1157 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1159 idx = found + MHSs->getValue().size();
1160 } while (found != std::string::npos);
1162 return StringInit::get(Val);
1169 Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1170 CurRec, CurMultiClass);
1178 IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
1179 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1180 LHSi = dynamic_cast<IntInit*>(I);
1182 if (LHSi->getValue()) {
1192 return const_cast<TernOpInit *>(this);
1195 Init *TernOpInit::resolveReferences(Record &R,
1196 const RecordVal *RV) const {
1197 Init *lhs = LHS->resolveReferences(R, RV);
1199 if (Opc == IF && lhs != LHS) {
1200 IntInit *Value = dynamic_cast<IntInit*>(lhs);
1201 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1202 Value = dynamic_cast<IntInit*>(I);
1205 if (Value->getValue()) {
1206 Init *mhs = MHS->resolveReferences(R, RV);
1207 return (TernOpInit::get(getOpcode(), lhs, mhs,
1208 RHS, getType()))->Fold(&R, 0);
1210 Init *rhs = RHS->resolveReferences(R, RV);
1211 return (TernOpInit::get(getOpcode(), lhs, MHS,
1212 rhs, getType()))->Fold(&R, 0);
1217 Init *mhs = MHS->resolveReferences(R, RV);
1218 Init *rhs = RHS->resolveReferences(R, RV);
1220 if (LHS != lhs || MHS != mhs || RHS != rhs)
1221 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1222 getType()))->Fold(&R, 0);
1226 std::string TernOpInit::getAsString() const {
1229 case SUBST: Result = "!subst"; break;
1230 case FOREACH: Result = "!foreach"; break;
1231 case IF: Result = "!if"; break;
1233 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
1234 + RHS->getAsString() + ")";
1237 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1238 RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType());
1240 RecordVal *Field = RecordType->getRecord()->getValue(FieldName);
1242 return Field->getType();
1249 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1250 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1251 if (T == 0) return 0; // Cannot subscript a non-bits variable.
1252 unsigned NumBits = T->getNumBits();
1254 SmallVector<Init *, 16> NewBits(Bits.size());
1255 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1256 if (Bits[i] >= NumBits)
1259 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1261 return BitsInit::get(NewBits);
1265 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1266 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1267 if (T == 0) return 0; // Cannot subscript a non-list variable.
1269 if (Elements.size() == 1)
1270 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1272 std::vector<Init*> ListInits;
1273 ListInits.reserve(Elements.size());
1274 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1275 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1277 return ListInit::get(ListInits, T);
1281 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1282 Init *Value = StringInit::get(VN);
1283 return VarInit::get(Value, T);
1286 VarInit *VarInit::get(Init *VN, RecTy *T) {
1287 typedef std::pair<RecTy *, Init *> Key;
1288 typedef DenseMap<Key, VarInit *> Pool;
1289 static Pool ThePool;
1291 Key TheKey(std::make_pair(T, VN));
1293 VarInit *&I = ThePool[TheKey];
1294 if (!I) I = new VarInit(VN, T);
1298 const std::string &VarInit::getName() const {
1299 StringInit *NameString =
1300 dynamic_cast<StringInit *>(getNameInit());
1301 assert(NameString && "VarInit name is not a string!");
1302 return NameString->getValue();
1305 Init *VarInit::getBit(unsigned Bit) const {
1306 if (getType() == BitRecTy::get())
1307 return const_cast<VarInit*>(this);
1308 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1311 Init *VarInit::resolveListElementReference(Record &R,
1312 const RecordVal *IRV,
1313 unsigned Elt) const {
1314 if (R.isTemplateArg(getNameInit())) return 0;
1315 if (IRV && IRV->getNameInit() != getNameInit()) return 0;
1317 RecordVal *RV = R.getValue(getNameInit());
1318 assert(RV && "Reference to a non-existent variable?");
1319 ListInit *LI = dynamic_cast<ListInit*>(RV->getValue());
1321 TypedInit *VI = dynamic_cast<TypedInit*>(RV->getValue());
1322 assert(VI && "Invalid list element!");
1323 return VarListElementInit::get(VI, Elt);
1326 if (Elt >= LI->getSize())
1327 return 0; // Out of range reference.
1328 Init *E = LI->getElement(Elt);
1329 // If the element is set to some value, or if we are resolving a reference
1330 // to a specific variable and that variable is explicitly unset, then
1331 // replace the VarListElementInit with it.
1332 if (IRV || !dynamic_cast<UnsetInit*>(E))
1338 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1339 if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
1340 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1341 return RV->getType();
1345 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1346 const std::string &FieldName) const {
1347 if (dyn_cast<RecordRecTy>(getType()))
1348 if (const RecordVal *Val = R.getValue(VarName)) {
1349 if (RV != Val && (RV || dynamic_cast<UnsetInit*>(Val->getValue())))
1351 Init *TheInit = Val->getValue();
1352 assert(TheInit != this && "Infinite loop detected!");
1353 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1361 /// resolveReferences - This method is used by classes that refer to other
1362 /// variables which may not be defined at the time the expression is formed.
1363 /// If a value is set for the variable later, this method will be called on
1364 /// users of the value to allow the value to propagate out.
1366 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1367 if (RecordVal *Val = R.getValue(VarName))
1368 if (RV == Val || (RV == 0 && !dynamic_cast<UnsetInit*>(Val->getValue())))
1369 return Val->getValue();
1370 return const_cast<VarInit *>(this);
1373 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1374 typedef std::pair<TypedInit *, unsigned> Key;
1375 typedef DenseMap<Key, VarBitInit *> Pool;
1377 static Pool ThePool;
1379 Key TheKey(std::make_pair(T, B));
1381 VarBitInit *&I = ThePool[TheKey];
1382 if (!I) I = new VarBitInit(T, B);
1386 std::string VarBitInit::getAsString() const {
1387 return TI->getAsString() + "{" + utostr(Bit) + "}";
1390 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1391 Init *I = TI->resolveReferences(R, RV);
1393 return I->getBit(getBitNum());
1395 return const_cast<VarBitInit*>(this);
1398 VarListElementInit *VarListElementInit::get(TypedInit *T,
1400 typedef std::pair<TypedInit *, unsigned> Key;
1401 typedef DenseMap<Key, VarListElementInit *> Pool;
1403 static Pool ThePool;
1405 Key TheKey(std::make_pair(T, E));
1407 VarListElementInit *&I = ThePool[TheKey];
1408 if (!I) I = new VarListElementInit(T, E);
1412 std::string VarListElementInit::getAsString() const {
1413 return TI->getAsString() + "[" + utostr(Element) + "]";
1417 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1418 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1421 return const_cast<VarListElementInit *>(this);
1424 Init *VarListElementInit::getBit(unsigned Bit) const {
1425 if (getType() == BitRecTy::get())
1426 return const_cast<VarListElementInit*>(this);
1427 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1430 Init *VarListElementInit:: resolveListElementReference(Record &R,
1431 const RecordVal *RV,
1432 unsigned Elt) const {
1433 Init *Result = TI->resolveListElementReference(R, RV, Element);
1436 TypedInit *TInit = dynamic_cast<TypedInit *>(Result);
1438 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1439 if (Result2) return Result2;
1440 return new VarListElementInit(TInit, Elt);
1448 DefInit *DefInit::get(Record *R) {
1449 return R->getDefInit();
1452 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1453 if (const RecordVal *RV = Def->getValue(FieldName))
1454 return RV->getType();
1458 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1459 const std::string &FieldName) const {
1460 return Def->getValue(FieldName)->getValue();
1464 std::string DefInit::getAsString() const {
1465 return Def->getName();
1468 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1469 typedef std::pair<Init *, TableGenStringKey> Key;
1470 typedef DenseMap<Key, FieldInit *> Pool;
1471 static Pool ThePool;
1473 Key TheKey(std::make_pair(R, FN));
1475 FieldInit *&I = ThePool[TheKey];
1476 if (!I) I = new FieldInit(R, FN);
1480 Init *FieldInit::getBit(unsigned Bit) const {
1481 if (getType() == BitRecTy::get())
1482 return const_cast<FieldInit*>(this);
1483 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1486 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1487 unsigned Elt) const {
1488 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1489 if (ListInit *LI = dynamic_cast<ListInit*>(ListVal)) {
1490 if (Elt >= LI->getSize()) return 0;
1491 Init *E = LI->getElement(Elt);
1493 // If the element is set to some value, or if we are resolving a
1494 // reference to a specific variable and that variable is explicitly
1495 // unset, then replace the VarListElementInit with it.
1496 if (RV || !dynamic_cast<UnsetInit*>(E))
1502 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1503 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1505 Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1507 Init *BVR = BitsVal->resolveReferences(R, RV);
1508 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1511 if (NewRec != Rec) {
1512 return FieldInit::get(NewRec, FieldName);
1514 return const_cast<FieldInit *>(this);
1517 void ProfileDagInit(FoldingSetNodeID &ID,
1519 const std::string &VN,
1520 ArrayRef<Init *> ArgRange,
1521 ArrayRef<std::string> NameRange) {
1525 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1526 ArrayRef<std::string>::iterator Name = NameRange.begin();
1527 while (Arg != ArgRange.end()) {
1528 assert(Name != NameRange.end() && "Arg name underflow!");
1529 ID.AddPointer(*Arg++);
1530 ID.AddString(*Name++);
1532 assert(Name == NameRange.end() && "Arg name overflow!");
1536 DagInit::get(Init *V, const std::string &VN,
1537 ArrayRef<Init *> ArgRange,
1538 ArrayRef<std::string> NameRange) {
1539 typedef FoldingSet<DagInit> Pool;
1540 static Pool ThePool;
1542 FoldingSetNodeID ID;
1543 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1546 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1549 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1550 ThePool.InsertNode(I, IP);
1556 DagInit::get(Init *V, const std::string &VN,
1557 const std::vector<std::pair<Init*, std::string> > &args) {
1558 typedef std::pair<Init*, std::string> PairType;
1560 std::vector<Init *> Args;
1561 std::vector<std::string> Names;
1563 for (std::vector<PairType>::const_iterator i = args.begin(),
1567 Args.push_back(i->first);
1568 Names.push_back(i->second);
1571 return DagInit::get(V, VN, Args, Names);
1574 void DagInit::Profile(FoldingSetNodeID &ID) const {
1575 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1578 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1579 std::vector<Init*> NewArgs;
1580 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1581 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1583 Init *Op = Val->resolveReferences(R, RV);
1585 if (Args != NewArgs || Op != Val)
1586 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1588 return const_cast<DagInit *>(this);
1592 std::string DagInit::getAsString() const {
1593 std::string Result = "(" + Val->getAsString();
1594 if (!ValName.empty())
1595 Result += ":" + ValName;
1597 Result += " " + Args[0]->getAsString();
1598 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1599 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1600 Result += ", " + Args[i]->getAsString();
1601 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1604 return Result + ")";
1608 //===----------------------------------------------------------------------===//
1609 // Other implementations
1610 //===----------------------------------------------------------------------===//
1612 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1613 : Name(N), Ty(T), Prefix(P) {
1614 Value = Ty->convertValue(UnsetInit::get());
1615 assert(Value && "Cannot create unset value for current type!");
1618 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1619 : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1620 Value = Ty->convertValue(UnsetInit::get());
1621 assert(Value && "Cannot create unset value for current type!");
1624 const std::string &RecordVal::getName() const {
1625 StringInit *NameString = dynamic_cast<StringInit *>(Name);
1626 assert(NameString && "RecordVal name is not a string!");
1627 return NameString->getValue();
1630 void RecordVal::dump() const { errs() << *this; }
1632 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1633 if (getPrefix()) OS << "field ";
1634 OS << *getType() << " " << getNameInitAsString();
1637 OS << " = " << *getValue();
1639 if (PrintSem) OS << ";\n";
1642 unsigned Record::LastID = 0;
1644 void Record::init() {
1647 // Every record potentially has a def at the top. This value is
1648 // replaced with the top-level def name at instantiation time.
1649 RecordVal DN("NAME", StringRecTy::get(), 0);
1653 void Record::checkName() {
1654 // Ensure the record name has string type.
1655 const TypedInit *TypedName = dynamic_cast<const TypedInit *>(Name);
1656 assert(TypedName && "Record name is not typed!");
1657 RecTy *Type = TypedName->getType();
1658 if (dyn_cast<StringRecTy>(Type) == 0) {
1659 throw TGError(getLoc(), "Record name is not a string!");
1663 DefInit *Record::getDefInit() {
1665 TheInit = new DefInit(this, new RecordRecTy(this));
1669 const std::string &Record::getName() const {
1670 const StringInit *NameString =
1671 dynamic_cast<const StringInit *>(Name);
1672 assert(NameString && "Record name is not a string!");
1673 return NameString->getValue();
1676 void Record::setName(Init *NewName) {
1677 if (TrackedRecords.getDef(Name->getAsUnquotedString()) == this) {
1678 TrackedRecords.removeDef(Name->getAsUnquotedString());
1679 TrackedRecords.addDef(this);
1680 } else if (TrackedRecords.getClass(Name->getAsUnquotedString()) == this) {
1681 TrackedRecords.removeClass(Name->getAsUnquotedString());
1682 TrackedRecords.addClass(this);
1683 } // Otherwise this isn't yet registered.
1686 // DO NOT resolve record values to the name at this point because
1687 // there might be default values for arguments of this def. Those
1688 // arguments might not have been resolved yet so we don't want to
1689 // prematurely assume values for those arguments were not passed to
1692 // Nonetheless, it may be that some of this Record's values
1693 // reference the record name. Indeed, the reason for having the
1694 // record name be an Init is to provide this flexibility. The extra
1695 // resolve steps after completely instantiating defs takes care of
1696 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1699 void Record::setName(const std::string &Name) {
1700 setName(StringInit::get(Name));
1703 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1704 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1706 void Record::resolveReferencesTo(const RecordVal *RV) {
1707 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1708 if (RV == &Values[i]) // Skip resolve the same field as the given one
1710 if (Init *V = Values[i].getValue())
1711 if (Values[i].setValue(V->resolveReferences(*this, RV)))
1712 throw TGError(getLoc(), "Invalid value is found when setting '"
1713 + Values[i].getNameInitAsString()
1714 + "' after resolving references"
1715 + (RV ? " against '" + RV->getNameInitAsString()
1717 + RV->getValue()->getAsUnquotedString() + ")"
1721 Init *OldName = getNameInit();
1722 Init *NewName = Name->resolveReferences(*this, RV);
1723 if (NewName != OldName) {
1724 // Re-register with RecordKeeper.
1729 void Record::dump() const { errs() << *this; }
1731 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1732 OS << R.getNameInitAsString();
1734 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1735 if (!TArgs.empty()) {
1737 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1739 const RecordVal *RV = R.getValue(TArgs[i]);
1740 assert(RV && "Template argument record not found??");
1741 RV->print(OS, false);
1747 const std::vector<Record*> &SC = R.getSuperClasses();
1750 for (unsigned i = 0, e = SC.size(); i != e; ++i)
1751 OS << " " << SC[i]->getNameInitAsString();
1755 const std::vector<RecordVal> &Vals = R.getValues();
1756 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1757 if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1759 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1760 if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1766 /// getValueInit - Return the initializer for a value with the specified name,
1767 /// or throw an exception if the field does not exist.
1769 Init *Record::getValueInit(StringRef FieldName) const {
1770 const RecordVal *R = getValue(FieldName);
1771 if (R == 0 || R->getValue() == 0)
1772 throw "Record `" + getName() + "' does not have a field named `" +
1773 FieldName.str() + "'!\n";
1774 return R->getValue();
1778 /// getValueAsString - This method looks up the specified field and returns its
1779 /// value as a string, throwing an exception if the field does not exist or if
1780 /// the value is not a string.
1782 std::string Record::getValueAsString(StringRef FieldName) const {
1783 const RecordVal *R = getValue(FieldName);
1784 if (R == 0 || R->getValue() == 0)
1785 throw "Record `" + getName() + "' does not have a field named `" +
1786 FieldName.str() + "'!\n";
1788 if (StringInit *SI = dynamic_cast<StringInit*>(R->getValue()))
1789 return SI->getValue();
1790 throw "Record `" + getName() + "', field `" + FieldName.str() +
1791 "' does not have a string initializer!";
1794 /// getValueAsBitsInit - This method looks up the specified field and returns
1795 /// its value as a BitsInit, throwing an exception if the field does not exist
1796 /// or if the value is not the right type.
1798 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1799 const RecordVal *R = getValue(FieldName);
1800 if (R == 0 || R->getValue() == 0)
1801 throw "Record `" + getName() + "' does not have a field named `" +
1802 FieldName.str() + "'!\n";
1804 if (BitsInit *BI = dynamic_cast<BitsInit*>(R->getValue()))
1806 throw "Record `" + getName() + "', field `" + FieldName.str() +
1807 "' does not have a BitsInit initializer!";
1810 /// getValueAsListInit - This method looks up the specified field and returns
1811 /// its value as a ListInit, throwing an exception if the field does not exist
1812 /// or if the value is not the right type.
1814 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1815 const RecordVal *R = getValue(FieldName);
1816 if (R == 0 || R->getValue() == 0)
1817 throw "Record `" + getName() + "' does not have a field named `" +
1818 FieldName.str() + "'!\n";
1820 if (ListInit *LI = dynamic_cast<ListInit*>(R->getValue()))
1822 throw "Record `" + getName() + "', field `" + FieldName.str() +
1823 "' does not have a list initializer!";
1826 /// getValueAsListOfDefs - This method looks up the specified field and returns
1827 /// its value as a vector of records, throwing an exception if the field does
1828 /// not exist or if the value is not the right type.
1830 std::vector<Record*>
1831 Record::getValueAsListOfDefs(StringRef FieldName) const {
1832 ListInit *List = getValueAsListInit(FieldName);
1833 std::vector<Record*> Defs;
1834 for (unsigned i = 0; i < List->getSize(); i++) {
1835 if (DefInit *DI = dynamic_cast<DefInit*>(List->getElement(i))) {
1836 Defs.push_back(DI->getDef());
1838 throw "Record `" + getName() + "', field `" + FieldName.str() +
1839 "' list is not entirely DefInit!";
1845 /// getValueAsInt - This method looks up the specified field and returns its
1846 /// value as an int64_t, throwing an exception if the field does not exist or if
1847 /// the value is not the right type.
1849 int64_t Record::getValueAsInt(StringRef FieldName) const {
1850 const RecordVal *R = getValue(FieldName);
1851 if (R == 0 || R->getValue() == 0)
1852 throw "Record `" + getName() + "' does not have a field named `" +
1853 FieldName.str() + "'!\n";
1855 if (IntInit *II = dynamic_cast<IntInit*>(R->getValue()))
1856 return II->getValue();
1857 throw "Record `" + getName() + "', field `" + FieldName.str() +
1858 "' does not have an int initializer!";
1861 /// getValueAsListOfInts - This method looks up the specified field and returns
1862 /// its value as a vector of integers, throwing an exception if the field does
1863 /// not exist or if the value is not the right type.
1865 std::vector<int64_t>
1866 Record::getValueAsListOfInts(StringRef FieldName) const {
1867 ListInit *List = getValueAsListInit(FieldName);
1868 std::vector<int64_t> Ints;
1869 for (unsigned i = 0; i < List->getSize(); i++) {
1870 if (IntInit *II = dynamic_cast<IntInit*>(List->getElement(i))) {
1871 Ints.push_back(II->getValue());
1873 throw "Record `" + getName() + "', field `" + FieldName.str() +
1874 "' does not have a list of ints initializer!";
1880 /// getValueAsListOfStrings - This method looks up the specified field and
1881 /// returns its value as a vector of strings, throwing an exception if the
1882 /// field does not exist or if the value is not the right type.
1884 std::vector<std::string>
1885 Record::getValueAsListOfStrings(StringRef FieldName) const {
1886 ListInit *List = getValueAsListInit(FieldName);
1887 std::vector<std::string> Strings;
1888 for (unsigned i = 0; i < List->getSize(); i++) {
1889 if (StringInit *II = dynamic_cast<StringInit*>(List->getElement(i))) {
1890 Strings.push_back(II->getValue());
1892 throw "Record `" + getName() + "', field `" + FieldName.str() +
1893 "' does not have a list of strings initializer!";
1899 /// getValueAsDef - This method looks up the specified field and returns its
1900 /// value as a Record, throwing an exception if the field does not exist or if
1901 /// the value is not the right type.
1903 Record *Record::getValueAsDef(StringRef FieldName) const {
1904 const RecordVal *R = getValue(FieldName);
1905 if (R == 0 || R->getValue() == 0)
1906 throw "Record `" + getName() + "' does not have a field named `" +
1907 FieldName.str() + "'!\n";
1909 if (DefInit *DI = dynamic_cast<DefInit*>(R->getValue()))
1910 return DI->getDef();
1911 throw "Record `" + getName() + "', field `" + FieldName.str() +
1912 "' does not have a def initializer!";
1915 /// getValueAsBit - This method looks up the specified field and returns its
1916 /// value as a bit, throwing an exception if the field does not exist or if
1917 /// the value is not the right type.
1919 bool Record::getValueAsBit(StringRef FieldName) const {
1920 const RecordVal *R = getValue(FieldName);
1921 if (R == 0 || R->getValue() == 0)
1922 throw "Record `" + getName() + "' does not have a field named `" +
1923 FieldName.str() + "'!\n";
1925 if (BitInit *BI = dynamic_cast<BitInit*>(R->getValue()))
1926 return BI->getValue();
1927 throw "Record `" + getName() + "', field `" + FieldName.str() +
1928 "' does not have a bit initializer!";
1931 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1932 const RecordVal *R = getValue(FieldName);
1933 if (R == 0 || R->getValue() == 0)
1934 throw "Record `" + getName() + "' does not have a field named `" +
1935 FieldName.str() + "'!\n";
1937 if (R->getValue() == UnsetInit::get()) {
1942 if (BitInit *BI = dynamic_cast<BitInit*>(R->getValue()))
1943 return BI->getValue();
1944 throw "Record `" + getName() + "', field `" + FieldName.str() +
1945 "' does not have a bit initializer!";
1948 /// getValueAsDag - This method looks up the specified field and returns its
1949 /// value as an Dag, throwing an exception if the field does not exist or if
1950 /// the value is not the right type.
1952 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1953 const RecordVal *R = getValue(FieldName);
1954 if (R == 0 || R->getValue() == 0)
1955 throw "Record `" + getName() + "' does not have a field named `" +
1956 FieldName.str() + "'!\n";
1958 if (DagInit *DI = dynamic_cast<DagInit*>(R->getValue()))
1960 throw "Record `" + getName() + "', field `" + FieldName.str() +
1961 "' does not have a dag initializer!";
1965 void MultiClass::dump() const {
1966 errs() << "Record:\n";
1969 errs() << "Defs:\n";
1970 for (RecordVector::const_iterator r = DefPrototypes.begin(),
1971 rend = DefPrototypes.end();
1979 void RecordKeeper::dump() const { errs() << *this; }
1981 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1982 OS << "------------- Classes -----------------\n";
1983 const std::map<std::string, Record*> &Classes = RK.getClasses();
1984 for (std::map<std::string, Record*>::const_iterator I = Classes.begin(),
1985 E = Classes.end(); I != E; ++I)
1986 OS << "class " << *I->second;
1988 OS << "------------- Defs -----------------\n";
1989 const std::map<std::string, Record*> &Defs = RK.getDefs();
1990 for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),
1991 E = Defs.end(); I != E; ++I)
1992 OS << "def " << *I->second;
1997 /// getAllDerivedDefinitions - This method returns all concrete definitions
1998 /// that derive from the specified class name. If a class with the specified
1999 /// name does not exist, an error is printed and true is returned.
2000 std::vector<Record*>
2001 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
2002 Record *Class = getClass(ClassName);
2004 throw "ERROR: Couldn't find the `" + ClassName + "' class!\n";
2006 std::vector<Record*> Defs;
2007 for (std::map<std::string, Record*>::const_iterator I = getDefs().begin(),
2008 E = getDefs().end(); I != E; ++I)
2009 if (I->second->isSubClassOf(Class))
2010 Defs.push_back(I->second);
2015 /// QualifyName - Return an Init with a qualifier prefix referring
2016 /// to CurRec's name.
2017 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2018 Init *Name, const std::string &Scoper) {
2019 RecTy *Type = dynamic_cast<TypedInit *>(Name)->getType();
2021 BinOpInit *NewName =
2022 BinOpInit::get(BinOpInit::STRCONCAT,
2023 BinOpInit::get(BinOpInit::STRCONCAT,
2024 CurRec.getNameInit(),
2025 StringInit::get(Scoper),
2026 Type)->Fold(&CurRec, CurMultiClass),
2030 if (CurMultiClass && Scoper != "::") {
2032 BinOpInit::get(BinOpInit::STRCONCAT,
2033 BinOpInit::get(BinOpInit::STRCONCAT,
2034 CurMultiClass->Rec.getNameInit(),
2035 StringInit::get("::"),
2036 Type)->Fold(&CurRec, CurMultiClass),
2037 NewName->Fold(&CurRec, CurMultiClass),
2041 return NewName->Fold(&CurRec, CurMultiClass);
2044 /// QualifyName - Return an Init with a qualifier prefix referring
2045 /// to CurRec's name.
2046 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2047 const std::string &Name,
2048 const std::string &Scoper) {
2049 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);