1 //===- Record.cpp - Record implementation ---------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implement the tablegen record classes.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/FoldingSet.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/Support/Allocator.h"
23 #include "llvm/Support/Casting.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/SMLoc.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/TableGen/Error.h"
29 #include "llvm/TableGen/Record.h"
30 #include <cassert>
31 #include <cstdint>
32 #include <memory>
33 #include <string>
34 #include <utility>
35 #include <vector>
36 
37 using namespace llvm;
38 
39 static BumpPtrAllocator Allocator;
40 
41 //===----------------------------------------------------------------------===//
42 //    Type implementations
43 //===----------------------------------------------------------------------===//
44 
45 BitRecTy BitRecTy::Shared;
46 CodeRecTy CodeRecTy::Shared;
47 IntRecTy IntRecTy::Shared;
48 StringRecTy StringRecTy::Shared;
49 DagRecTy DagRecTy::Shared;
50 
51 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
52 LLVM_DUMP_METHOD void RecTy::dump() const { print(errs()); }
53 #endif
54 
55 ListRecTy *RecTy::getListTy() {
56   if (!ListTy)
57     ListTy = new(Allocator) ListRecTy(this);
58   return ListTy;
59 }
60 
61 bool RecTy::typeIsConvertibleTo(const RecTy *RHS) const {
62   assert(RHS && "NULL pointer");
63   return Kind == RHS->getRecTyKind();
64 }
65 
66 bool RecTy::typeIsA(const RecTy *RHS) const { return this == RHS; }
67 
68 bool BitRecTy::typeIsConvertibleTo(const RecTy *RHS) const{
69   if (RecTy::typeIsConvertibleTo(RHS) || RHS->getRecTyKind() == IntRecTyKind)
70     return true;
71   if (const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
72     return BitsTy->getNumBits() == 1;
73   return false;
74 }
75 
76 BitsRecTy *BitsRecTy::get(unsigned Sz) {
77   static std::vector<BitsRecTy*> Shared;
78   if (Sz >= Shared.size())
79     Shared.resize(Sz + 1);
80   BitsRecTy *&Ty = Shared[Sz];
81   if (!Ty)
82     Ty = new(Allocator) BitsRecTy(Sz);
83   return Ty;
84 }
85 
86 std::string BitsRecTy::getAsString() const {
87   return "bits<" + utostr(Size) + ">";
88 }
89 
90 bool BitsRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
91   if (RecTy::typeIsConvertibleTo(RHS)) //argument and the sender are same type
92     return cast<BitsRecTy>(RHS)->Size == Size;
93   RecTyKind kind = RHS->getRecTyKind();
94   return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
95 }
96 
97 bool BitsRecTy::typeIsA(const RecTy *RHS) const {
98   if (const BitsRecTy *RHSb = dyn_cast<BitsRecTy>(RHS))
99     return RHSb->Size == Size;
100   return false;
101 }
102 
103 bool IntRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
104   RecTyKind kind = RHS->getRecTyKind();
105   return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
106 }
107 
108 bool CodeRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
109   RecTyKind Kind = RHS->getRecTyKind();
110   return Kind == CodeRecTyKind || Kind == StringRecTyKind;
111 }
112 
113 std::string StringRecTy::getAsString() const {
114   return "string";
115 }
116 
117 bool StringRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
118   RecTyKind Kind = RHS->getRecTyKind();
119   return Kind == StringRecTyKind || Kind == CodeRecTyKind;
120 }
121 
122 std::string ListRecTy::getAsString() const {
123   return "list<" + Ty->getAsString() + ">";
124 }
125 
126 bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
127   if (const auto *ListTy = dyn_cast<ListRecTy>(RHS))
128     return Ty->typeIsConvertibleTo(ListTy->getElementType());
129   return false;
130 }
131 
132 bool ListRecTy::typeIsA(const RecTy *RHS) const {
133   if (const ListRecTy *RHSl = dyn_cast<ListRecTy>(RHS))
134     return getElementType()->typeIsA(RHSl->getElementType());
135   return false;
136 }
137 
138 std::string DagRecTy::getAsString() const {
139   return "dag";
140 }
141 
142 static void ProfileRecordRecTy(FoldingSetNodeID &ID,
143                                ArrayRef<Record *> Classes) {
144   ID.AddInteger(Classes.size());
145   for (Record *R : Classes)
146     ID.AddPointer(R);
147 }
148 
149 RecordRecTy *RecordRecTy::get(ArrayRef<Record *> UnsortedClasses) {
150   if (UnsortedClasses.empty()) {
151     static RecordRecTy AnyRecord(0);
152     return &AnyRecord;
153   }
154 
155   FoldingSet<RecordRecTy> &ThePool =
156       UnsortedClasses[0]->getRecords().RecordTypePool;
157 
158   SmallVector<Record *, 4> Classes(UnsortedClasses.begin(),
159                                    UnsortedClasses.end());
160   llvm::sort(Classes.begin(), Classes.end(),
161              [](Record *LHS, Record *RHS) {
162                return LHS->getNameInitAsString() < RHS->getNameInitAsString();
163              });
164 
165   FoldingSetNodeID ID;
166   ProfileRecordRecTy(ID, Classes);
167 
168   void *IP = nullptr;
169   if (RecordRecTy *Ty = ThePool.FindNodeOrInsertPos(ID, IP))
170     return Ty;
171 
172 #ifndef NDEBUG
173   // Check for redundancy.
174   for (unsigned i = 0; i < Classes.size(); ++i) {
175     for (unsigned j = 0; j < Classes.size(); ++j) {
176       assert(i == j || !Classes[i]->isSubClassOf(Classes[j]));
177     }
178     assert(&Classes[0]->getRecords() == &Classes[i]->getRecords());
179   }
180 #endif
181 
182   void *Mem = Allocator.Allocate(totalSizeToAlloc<Record *>(Classes.size()),
183                                  alignof(RecordRecTy));
184   RecordRecTy *Ty = new(Mem) RecordRecTy(Classes.size());
185   std::uninitialized_copy(Classes.begin(), Classes.end(),
186                           Ty->getTrailingObjects<Record *>());
187   ThePool.InsertNode(Ty, IP);
188   return Ty;
189 }
190 
191 void RecordRecTy::Profile(FoldingSetNodeID &ID) const {
192   ProfileRecordRecTy(ID, getClasses());
193 }
194 
195 std::string RecordRecTy::getAsString() const {
196   if (NumClasses == 1)
197     return getClasses()[0]->getNameInitAsString();
198 
199   std::string Str = "{";
200   bool First = true;
201   for (Record *R : getClasses()) {
202     if (!First)
203       Str += ", ";
204     First = false;
205     Str += R->getNameInitAsString();
206   }
207   Str += "}";
208   return Str;
209 }
210 
211 bool RecordRecTy::isSubClassOf(Record *Class) const {
212   return llvm::any_of(getClasses(), [Class](Record *MySuperClass) {
213                                       return MySuperClass == Class ||
214                                              MySuperClass->isSubClassOf(Class);
215                                     });
216 }
217 
218 bool RecordRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
219   if (this == RHS)
220     return true;
221 
222   const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
223   if (!RTy)
224     return false;
225 
226   return llvm::all_of(RTy->getClasses(), [this](Record *TargetClass) {
227                                            return isSubClassOf(TargetClass);
228                                          });
229 }
230 
231 bool RecordRecTy::typeIsA(const RecTy *RHS) const {
232   return typeIsConvertibleTo(RHS);
233 }
234 
235 static RecordRecTy *resolveRecordTypes(RecordRecTy *T1, RecordRecTy *T2) {
236   SmallVector<Record *, 4> CommonSuperClasses;
237   SmallVector<Record *, 4> Stack;
238 
239   Stack.insert(Stack.end(), T1->classes_begin(), T1->classes_end());
240 
241   while (!Stack.empty()) {
242     Record *R = Stack.back();
243     Stack.pop_back();
244 
245     if (T2->isSubClassOf(R)) {
246       CommonSuperClasses.push_back(R);
247     } else {
248       R->getDirectSuperClasses(Stack);
249     }
250   }
251 
252   return RecordRecTy::get(CommonSuperClasses);
253 }
254 
255 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
256   if (T1 == T2)
257     return T1;
258 
259   if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
260     if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2))
261       return resolveRecordTypes(RecTy1, RecTy2);
262   }
263 
264   if (T1->typeIsConvertibleTo(T2))
265     return T2;
266   if (T2->typeIsConvertibleTo(T1))
267     return T1;
268 
269   if (ListRecTy *ListTy1 = dyn_cast<ListRecTy>(T1)) {
270     if (ListRecTy *ListTy2 = dyn_cast<ListRecTy>(T2)) {
271       RecTy* NewType = resolveTypes(ListTy1->getElementType(),
272                                     ListTy2->getElementType());
273       if (NewType)
274         return NewType->getListTy();
275     }
276   }
277 
278   return nullptr;
279 }
280 
281 //===----------------------------------------------------------------------===//
282 //    Initializer implementations
283 //===----------------------------------------------------------------------===//
284 
285 void Init::anchor() {}
286 
287 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
288 LLVM_DUMP_METHOD void Init::dump() const { return print(errs()); }
289 #endif
290 
291 UnsetInit *UnsetInit::get() {
292   static UnsetInit TheInit;
293   return &TheInit;
294 }
295 
296 Init *UnsetInit::getCastTo(RecTy *Ty) const {
297   return const_cast<UnsetInit *>(this);
298 }
299 
300 Init *UnsetInit::convertInitializerTo(RecTy *Ty) const {
301   return const_cast<UnsetInit *>(this);
302 }
303 
304 BitInit *BitInit::get(bool V) {
305   static BitInit True(true);
306   static BitInit False(false);
307 
308   return V ? &True : &False;
309 }
310 
311 Init *BitInit::convertInitializerTo(RecTy *Ty) const {
312   if (isa<BitRecTy>(Ty))
313     return const_cast<BitInit *>(this);
314 
315   if (isa<IntRecTy>(Ty))
316     return IntInit::get(getValue());
317 
318   if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
319     // Can only convert single bit.
320     if (BRT->getNumBits() == 1)
321       return BitsInit::get(const_cast<BitInit *>(this));
322   }
323 
324   return nullptr;
325 }
326 
327 static void
328 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
329   ID.AddInteger(Range.size());
330 
331   for (Init *I : Range)
332     ID.AddPointer(I);
333 }
334 
335 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
336   static FoldingSet<BitsInit> ThePool;
337 
338   FoldingSetNodeID ID;
339   ProfileBitsInit(ID, Range);
340 
341   void *IP = nullptr;
342   if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
343     return I;
344 
345   void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),
346                                  alignof(BitsInit));
347   BitsInit *I = new(Mem) BitsInit(Range.size());
348   std::uninitialized_copy(Range.begin(), Range.end(),
349                           I->getTrailingObjects<Init *>());
350   ThePool.InsertNode(I, IP);
351   return I;
352 }
353 
354 void BitsInit::Profile(FoldingSetNodeID &ID) const {
355   ProfileBitsInit(ID, makeArrayRef(getTrailingObjects<Init *>(), NumBits));
356 }
357 
358 Init *BitsInit::convertInitializerTo(RecTy *Ty) const {
359   if (isa<BitRecTy>(Ty)) {
360     if (getNumBits() != 1) return nullptr; // Only accept if just one bit!
361     return getBit(0);
362   }
363 
364   if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
365     // If the number of bits is right, return it.  Otherwise we need to expand
366     // or truncate.
367     if (getNumBits() != BRT->getNumBits()) return nullptr;
368     return const_cast<BitsInit *>(this);
369   }
370 
371   if (isa<IntRecTy>(Ty)) {
372     int64_t Result = 0;
373     for (unsigned i = 0, e = getNumBits(); i != e; ++i)
374       if (auto *Bit = dyn_cast<BitInit>(getBit(i)))
375         Result |= static_cast<int64_t>(Bit->getValue()) << i;
376       else
377         return nullptr;
378     return IntInit::get(Result);
379   }
380 
381   return nullptr;
382 }
383 
384 Init *
385 BitsInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
386   SmallVector<Init *, 16> NewBits(Bits.size());
387 
388   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
389     if (Bits[i] >= getNumBits())
390       return nullptr;
391     NewBits[i] = getBit(Bits[i]);
392   }
393   return BitsInit::get(NewBits);
394 }
395 
396 bool BitsInit::isConcrete() const {
397   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
398     if (!getBit(i)->isConcrete())
399       return false;
400   }
401   return true;
402 }
403 
404 std::string BitsInit::getAsString() const {
405   std::string Result = "{ ";
406   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
407     if (i) Result += ", ";
408     if (Init *Bit = getBit(e-i-1))
409       Result += Bit->getAsString();
410     else
411       Result += "*";
412   }
413   return Result + " }";
414 }
415 
416 // resolveReferences - If there are any field references that refer to fields
417 // that have been filled in, we can propagate the values now.
418 Init *BitsInit::resolveReferences(Resolver &R) const {
419   bool Changed = false;
420   SmallVector<Init *, 16> NewBits(getNumBits());
421 
422   Init *CachedBitVarRef = nullptr;
423   Init *CachedBitVarResolved = nullptr;
424 
425   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
426     Init *CurBit = getBit(i);
427     Init *NewBit = CurBit;
428 
429     if (VarBitInit *CurBitVar = dyn_cast<VarBitInit>(CurBit)) {
430       if (CurBitVar->getBitVar() != CachedBitVarRef) {
431         CachedBitVarRef = CurBitVar->getBitVar();
432         CachedBitVarResolved = CachedBitVarRef->resolveReferences(R);
433       }
434 
435       NewBit = CachedBitVarResolved->getBit(CurBitVar->getBitNum());
436     } else {
437       // getBit(0) implicitly converts int and bits<1> values to bit.
438       NewBit = CurBit->resolveReferences(R)->getBit(0);
439     }
440 
441     if (isa<UnsetInit>(NewBit) && R.keepUnsetBits())
442       NewBit = CurBit;
443     NewBits[i] = NewBit;
444     Changed |= CurBit != NewBit;
445   }
446 
447   if (Changed)
448     return BitsInit::get(NewBits);
449 
450   return const_cast<BitsInit *>(this);
451 }
452 
453 IntInit *IntInit::get(int64_t V) {
454   static DenseMap<int64_t, IntInit*> ThePool;
455 
456   IntInit *&I = ThePool[V];
457   if (!I) I = new(Allocator) IntInit(V);
458   return I;
459 }
460 
461 std::string IntInit::getAsString() const {
462   return itostr(Value);
463 }
464 
465 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
466   // For example, with NumBits == 4, we permit Values from [-7 .. 15].
467   return (NumBits >= sizeof(Value) * 8) ||
468          (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
469 }
470 
471 Init *IntInit::convertInitializerTo(RecTy *Ty) const {
472   if (isa<IntRecTy>(Ty))
473     return const_cast<IntInit *>(this);
474 
475   if (isa<BitRecTy>(Ty)) {
476     int64_t Val = getValue();
477     if (Val != 0 && Val != 1) return nullptr;  // Only accept 0 or 1 for a bit!
478     return BitInit::get(Val != 0);
479   }
480 
481   if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
482     int64_t Value = getValue();
483     // Make sure this bitfield is large enough to hold the integer value.
484     if (!canFitInBitfield(Value, BRT->getNumBits()))
485       return nullptr;
486 
487     SmallVector<Init *, 16> NewBits(BRT->getNumBits());
488     for (unsigned i = 0; i != BRT->getNumBits(); ++i)
489       NewBits[i] = BitInit::get(Value & (1LL << i));
490 
491     return BitsInit::get(NewBits);
492   }
493 
494   return nullptr;
495 }
496 
497 Init *
498 IntInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
499   SmallVector<Init *, 16> NewBits(Bits.size());
500 
501   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
502     if (Bits[i] >= 64)
503       return nullptr;
504 
505     NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
506   }
507   return BitsInit::get(NewBits);
508 }
509 
510 CodeInit *CodeInit::get(StringRef V) {
511   static StringMap<CodeInit*, BumpPtrAllocator &> ThePool(Allocator);
512 
513   auto &Entry = *ThePool.insert(std::make_pair(V, nullptr)).first;
514   if (!Entry.second)
515     Entry.second = new(Allocator) CodeInit(Entry.getKey());
516   return Entry.second;
517 }
518 
519 StringInit *StringInit::get(StringRef V) {
520   static StringMap<StringInit*, BumpPtrAllocator &> ThePool(Allocator);
521 
522   auto &Entry = *ThePool.insert(std::make_pair(V, nullptr)).first;
523   if (!Entry.second)
524     Entry.second = new(Allocator) StringInit(Entry.getKey());
525   return Entry.second;
526 }
527 
528 Init *StringInit::convertInitializerTo(RecTy *Ty) const {
529   if (isa<StringRecTy>(Ty))
530     return const_cast<StringInit *>(this);
531   if (isa<CodeRecTy>(Ty))
532     return CodeInit::get(getValue());
533 
534   return nullptr;
535 }
536 
537 Init *CodeInit::convertInitializerTo(RecTy *Ty) const {
538   if (isa<CodeRecTy>(Ty))
539     return const_cast<CodeInit *>(this);
540   if (isa<StringRecTy>(Ty))
541     return StringInit::get(getValue());
542 
543   return nullptr;
544 }
545 
546 static void ProfileListInit(FoldingSetNodeID &ID,
547                             ArrayRef<Init *> Range,
548                             RecTy *EltTy) {
549   ID.AddInteger(Range.size());
550   ID.AddPointer(EltTy);
551 
552   for (Init *I : Range)
553     ID.AddPointer(I);
554 }
555 
556 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
557   static FoldingSet<ListInit> ThePool;
558 
559   FoldingSetNodeID ID;
560   ProfileListInit(ID, Range, EltTy);
561 
562   void *IP = nullptr;
563   if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
564     return I;
565 
566   assert(Range.empty() || !isa<TypedInit>(Range[0]) ||
567          cast<TypedInit>(Range[0])->getType()->typeIsConvertibleTo(EltTy));
568 
569   void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),
570                                  alignof(ListInit));
571   ListInit *I = new(Mem) ListInit(Range.size(), EltTy);
572   std::uninitialized_copy(Range.begin(), Range.end(),
573                           I->getTrailingObjects<Init *>());
574   ThePool.InsertNode(I, IP);
575   return I;
576 }
577 
578 void ListInit::Profile(FoldingSetNodeID &ID) const {
579   RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
580 
581   ProfileListInit(ID, getValues(), EltTy);
582 }
583 
584 Init *ListInit::convertInitializerTo(RecTy *Ty) const {
585   if (getType() == Ty)
586     return const_cast<ListInit*>(this);
587 
588   if (auto *LRT = dyn_cast<ListRecTy>(Ty)) {
589     SmallVector<Init*, 8> Elements;
590     Elements.reserve(getValues().size());
591 
592     // Verify that all of the elements of the list are subclasses of the
593     // appropriate class!
594     bool Changed = false;
595     RecTy *ElementType = LRT->getElementType();
596     for (Init *I : getValues())
597       if (Init *CI = I->convertInitializerTo(ElementType)) {
598         Elements.push_back(CI);
599         if (CI != I)
600           Changed = true;
601       } else
602         return nullptr;
603 
604     if (!Changed)
605       return const_cast<ListInit*>(this);
606     return ListInit::get(Elements, ElementType);
607   }
608 
609   return nullptr;
610 }
611 
612 Init *ListInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
613   SmallVector<Init*, 8> Vals;
614   Vals.reserve(Elements.size());
615   for (unsigned Element : Elements) {
616     if (Element >= size())
617       return nullptr;
618     Vals.push_back(getElement(Element));
619   }
620   return ListInit::get(Vals, getElementType());
621 }
622 
623 Record *ListInit::getElementAsRecord(unsigned i) const {
624   assert(i < NumValues && "List element index out of range!");
625   DefInit *DI = dyn_cast<DefInit>(getElement(i));
626   if (!DI)
627     PrintFatalError("Expected record in list!");
628   return DI->getDef();
629 }
630 
631 Init *ListInit::resolveReferences(Resolver &R) const {
632   SmallVector<Init*, 8> Resolved;
633   Resolved.reserve(size());
634   bool Changed = false;
635 
636   for (Init *CurElt : getValues()) {
637     Init *E = CurElt->resolveReferences(R);
638     Changed |= E != CurElt;
639     Resolved.push_back(E);
640   }
641 
642   if (Changed)
643     return ListInit::get(Resolved, getElementType());
644   return const_cast<ListInit *>(this);
645 }
646 
647 bool ListInit::isConcrete() const {
648   for (Init *Element : *this) {
649     if (!Element->isConcrete())
650       return false;
651   }
652   return true;
653 }
654 
655 std::string ListInit::getAsString() const {
656   std::string Result = "[";
657   const char *sep = "";
658   for (Init *Element : *this) {
659     Result += sep;
660     sep = ", ";
661     Result += Element->getAsString();
662   }
663   return Result + "]";
664 }
665 
666 Init *OpInit::getBit(unsigned Bit) const {
667   if (getType() == BitRecTy::get())
668     return const_cast<OpInit*>(this);
669   return VarBitInit::get(const_cast<OpInit*>(this), Bit);
670 }
671 
672 static void
673 ProfileUnOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *Op, RecTy *Type) {
674   ID.AddInteger(Opcode);
675   ID.AddPointer(Op);
676   ID.AddPointer(Type);
677 }
678 
679 UnOpInit *UnOpInit::get(UnaryOp Opc, Init *LHS, RecTy *Type) {
680   static FoldingSet<UnOpInit> ThePool;
681 
682   FoldingSetNodeID ID;
683   ProfileUnOpInit(ID, Opc, LHS, Type);
684 
685   void *IP = nullptr;
686   if (UnOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
687     return I;
688 
689   UnOpInit *I = new(Allocator) UnOpInit(Opc, LHS, Type);
690   ThePool.InsertNode(I, IP);
691   return I;
692 }
693 
694 void UnOpInit::Profile(FoldingSetNodeID &ID) const {
695   ProfileUnOpInit(ID, getOpcode(), getOperand(), getType());
696 }
697 
698 Init *UnOpInit::Fold(Record *CurRec, bool IsFinal) const {
699   switch (getOpcode()) {
700   case CAST:
701     if (isa<StringRecTy>(getType())) {
702       if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
703         return LHSs;
704 
705       if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
706         return StringInit::get(LHSd->getAsString());
707 
708       if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
709         return StringInit::get(LHSi->getAsString());
710     } else if (isa<RecordRecTy>(getType())) {
711       if (StringInit *Name = dyn_cast<StringInit>(LHS)) {
712         assert(CurRec && "NULL pointer");
713         Record *D;
714 
715         // Self-references are allowed, but their resolution is delayed until
716         // the final resolve to ensure that we get the correct type for them.
717         if (Name == CurRec->getNameInit()) {
718           if (!IsFinal)
719             break;
720           D = CurRec;
721         } else {
722           D = CurRec->getRecords().getDef(Name->getValue());
723           if (!D) {
724             if (IsFinal)
725               PrintFatalError(CurRec->getLoc(),
726                               Twine("Undefined reference to record: '") +
727                               Name->getValue() + "'\n");
728             break;
729           }
730         }
731 
732         DefInit *DI = DefInit::get(D);
733         if (!DI->getType()->typeIsA(getType())) {
734           PrintFatalError(CurRec->getLoc(),
735                           Twine("Expected type '") +
736                           getType()->getAsString() + "', got '" +
737                           DI->getType()->getAsString() + "' in: " +
738                           getAsString() + "\n");
739         }
740         return DI;
741       }
742     }
743 
744     if (Init *NewInit = LHS->convertInitializerTo(getType()))
745       return NewInit;
746     break;
747 
748   case HEAD:
749     if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
750       assert(!LHSl->empty() && "Empty list in head");
751       return LHSl->getElement(0);
752     }
753     break;
754 
755   case TAIL:
756     if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
757       assert(!LHSl->empty() && "Empty list in tail");
758       // Note the +1.  We can't just pass the result of getValues()
759       // directly.
760       return ListInit::get(LHSl->getValues().slice(1), LHSl->getElementType());
761     }
762     break;
763 
764   case SIZE:
765     if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
766       return IntInit::get(LHSl->size());
767     break;
768 
769   case EMPTY:
770     if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
771       return IntInit::get(LHSl->empty());
772     if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
773       return IntInit::get(LHSs->getValue().empty());
774     break;
775   }
776   return const_cast<UnOpInit *>(this);
777 }
778 
779 Init *UnOpInit::resolveReferences(Resolver &R) const {
780   Init *lhs = LHS->resolveReferences(R);
781 
782   if (LHS != lhs || (R.isFinal() && getOpcode() == CAST))
783     return (UnOpInit::get(getOpcode(), lhs, getType()))
784         ->Fold(R.getCurrentRecord(), R.isFinal());
785   return const_cast<UnOpInit *>(this);
786 }
787 
788 std::string UnOpInit::getAsString() const {
789   std::string Result;
790   switch (getOpcode()) {
791   case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
792   case HEAD: Result = "!head"; break;
793   case TAIL: Result = "!tail"; break;
794   case SIZE: Result = "!size"; break;
795   case EMPTY: Result = "!empty"; break;
796   }
797   return Result + "(" + LHS->getAsString() + ")";
798 }
799 
800 static void
801 ProfileBinOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *RHS,
802                  RecTy *Type) {
803   ID.AddInteger(Opcode);
804   ID.AddPointer(LHS);
805   ID.AddPointer(RHS);
806   ID.AddPointer(Type);
807 }
808 
809 BinOpInit *BinOpInit::get(BinaryOp Opc, Init *LHS,
810                           Init *RHS, RecTy *Type) {
811   static FoldingSet<BinOpInit> ThePool;
812 
813   FoldingSetNodeID ID;
814   ProfileBinOpInit(ID, Opc, LHS, RHS, Type);
815 
816   void *IP = nullptr;
817   if (BinOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
818     return I;
819 
820   BinOpInit *I = new(Allocator) BinOpInit(Opc, LHS, RHS, Type);
821   ThePool.InsertNode(I, IP);
822   return I;
823 }
824 
825 void BinOpInit::Profile(FoldingSetNodeID &ID) const {
826   ProfileBinOpInit(ID, getOpcode(), getLHS(), getRHS(), getType());
827 }
828 
829 static StringInit *ConcatStringInits(const StringInit *I0,
830                                      const StringInit *I1) {
831   SmallString<80> Concat(I0->getValue());
832   Concat.append(I1->getValue());
833   return StringInit::get(Concat);
834 }
835 
836 Init *BinOpInit::getStrConcat(Init *I0, Init *I1) {
837   // Shortcut for the common case of concatenating two strings.
838   if (const StringInit *I0s = dyn_cast<StringInit>(I0))
839     if (const StringInit *I1s = dyn_cast<StringInit>(I1))
840       return ConcatStringInits(I0s, I1s);
841   return BinOpInit::get(BinOpInit::STRCONCAT, I0, I1, StringRecTy::get());
842 }
843 
844 Init *BinOpInit::Fold(Record *CurRec) const {
845   switch (getOpcode()) {
846   case CONCAT: {
847     DagInit *LHSs = dyn_cast<DagInit>(LHS);
848     DagInit *RHSs = dyn_cast<DagInit>(RHS);
849     if (LHSs && RHSs) {
850       DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
851       DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
852       if (!LOp || !ROp)
853         break;
854       if (LOp->getDef() != ROp->getDef()) {
855         PrintFatalError(Twine("Concatenated Dag operators do not match: '") +
856                         LHSs->getAsString() + "' vs. '" + RHSs->getAsString() +
857                         "'");
858       }
859       SmallVector<Init*, 8> Args;
860       SmallVector<StringInit*, 8> ArgNames;
861       for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
862         Args.push_back(LHSs->getArg(i));
863         ArgNames.push_back(LHSs->getArgName(i));
864       }
865       for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
866         Args.push_back(RHSs->getArg(i));
867         ArgNames.push_back(RHSs->getArgName(i));
868       }
869       return DagInit::get(LHSs->getOperator(), nullptr, Args, ArgNames);
870     }
871     break;
872   }
873   case LISTCONCAT: {
874     ListInit *LHSs = dyn_cast<ListInit>(LHS);
875     ListInit *RHSs = dyn_cast<ListInit>(RHS);
876     if (LHSs && RHSs) {
877       SmallVector<Init *, 8> Args;
878       Args.insert(Args.end(), LHSs->begin(), LHSs->end());
879       Args.insert(Args.end(), RHSs->begin(), RHSs->end());
880       return ListInit::get(Args, LHSs->getElementType());
881     }
882     break;
883   }
884   case STRCONCAT: {
885     StringInit *LHSs = dyn_cast<StringInit>(LHS);
886     StringInit *RHSs = dyn_cast<StringInit>(RHS);
887     if (LHSs && RHSs)
888       return ConcatStringInits(LHSs, RHSs);
889     break;
890   }
891   case EQ:
892   case NE:
893   case LE:
894   case LT:
895   case GE:
896   case GT: {
897     // try to fold eq comparison for 'bit' and 'int', otherwise fallback
898     // to string objects.
899     IntInit *L =
900         dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
901     IntInit *R =
902         dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
903 
904     if (L && R) {
905       bool Result;
906       switch (getOpcode()) {
907       case EQ: Result = L->getValue() == R->getValue(); break;
908       case NE: Result = L->getValue() != R->getValue(); break;
909       case LE: Result = L->getValue() <= R->getValue(); break;
910       case LT: Result = L->getValue() < R->getValue(); break;
911       case GE: Result = L->getValue() >= R->getValue(); break;
912       case GT: Result = L->getValue() > R->getValue(); break;
913       default: llvm_unreachable("unhandled comparison");
914       }
915       return BitInit::get(Result);
916     }
917 
918     if (getOpcode() == EQ || getOpcode() == NE) {
919       StringInit *LHSs = dyn_cast<StringInit>(LHS);
920       StringInit *RHSs = dyn_cast<StringInit>(RHS);
921 
922       // Make sure we've resolved
923       if (LHSs && RHSs) {
924         bool Equal = LHSs->getValue() == RHSs->getValue();
925         return BitInit::get(getOpcode() == EQ ? Equal : !Equal);
926       }
927     }
928 
929     break;
930   }
931   case ADD:
932   case AND:
933   case OR:
934   case SHL:
935   case SRA:
936   case SRL: {
937     IntInit *LHSi =
938       dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
939     IntInit *RHSi =
940       dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
941     if (LHSi && RHSi) {
942       int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
943       int64_t Result;
944       switch (getOpcode()) {
945       default: llvm_unreachable("Bad opcode!");
946       case ADD: Result = LHSv +  RHSv; break;
947       case AND: Result = LHSv &  RHSv; break;
948       case OR: Result = LHSv | RHSv; break;
949       case SHL: Result = LHSv << RHSv; break;
950       case SRA: Result = LHSv >> RHSv; break;
951       case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
952       }
953       return IntInit::get(Result);
954     }
955     break;
956   }
957   }
958   return const_cast<BinOpInit *>(this);
959 }
960 
961 Init *BinOpInit::resolveReferences(Resolver &R) const {
962   Init *lhs = LHS->resolveReferences(R);
963   Init *rhs = RHS->resolveReferences(R);
964 
965   if (LHS != lhs || RHS != rhs)
966     return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))
967         ->Fold(R.getCurrentRecord());
968   return const_cast<BinOpInit *>(this);
969 }
970 
971 std::string BinOpInit::getAsString() const {
972   std::string Result;
973   switch (getOpcode()) {
974   case CONCAT: Result = "!con"; break;
975   case ADD: Result = "!add"; break;
976   case AND: Result = "!and"; break;
977   case OR: Result = "!or"; break;
978   case SHL: Result = "!shl"; break;
979   case SRA: Result = "!sra"; break;
980   case SRL: Result = "!srl"; break;
981   case EQ: Result = "!eq"; break;
982   case NE: Result = "!ne"; break;
983   case LE: Result = "!le"; break;
984   case LT: Result = "!lt"; break;
985   case GE: Result = "!ge"; break;
986   case GT: Result = "!gt"; break;
987   case LISTCONCAT: Result = "!listconcat"; break;
988   case STRCONCAT: Result = "!strconcat"; break;
989   }
990   return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
991 }
992 
993 static void
994 ProfileTernOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *MHS,
995                   Init *RHS, RecTy *Type) {
996   ID.AddInteger(Opcode);
997   ID.AddPointer(LHS);
998   ID.AddPointer(MHS);
999   ID.AddPointer(RHS);
1000   ID.AddPointer(Type);
1001 }
1002 
1003 TernOpInit *TernOpInit::get(TernaryOp Opc, Init *LHS, Init *MHS, Init *RHS,
1004                             RecTy *Type) {
1005   static FoldingSet<TernOpInit> ThePool;
1006 
1007   FoldingSetNodeID ID;
1008   ProfileTernOpInit(ID, Opc, LHS, MHS, RHS, Type);
1009 
1010   void *IP = nullptr;
1011   if (TernOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1012     return I;
1013 
1014   TernOpInit *I = new(Allocator) TernOpInit(Opc, LHS, MHS, RHS, Type);
1015   ThePool.InsertNode(I, IP);
1016   return I;
1017 }
1018 
1019 void TernOpInit::Profile(FoldingSetNodeID &ID) const {
1020   ProfileTernOpInit(ID, getOpcode(), getLHS(), getMHS(), getRHS(), getType());
1021 }
1022 
1023 static Init *ForeachApply(Init *LHS, Init *MHSe, Init *RHS, Record *CurRec) {
1024   MapResolver R(CurRec);
1025   R.set(LHS, MHSe);
1026   return RHS->resolveReferences(R);
1027 }
1028 
1029 static Init *ForeachDagApply(Init *LHS, DagInit *MHSd, Init *RHS,
1030                              Record *CurRec) {
1031   bool Change = false;
1032   Init *Val = ForeachApply(LHS, MHSd->getOperator(), RHS, CurRec);
1033   if (Val != MHSd->getOperator())
1034     Change = true;
1035 
1036   SmallVector<std::pair<Init *, StringInit *>, 8> NewArgs;
1037   for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1038     Init *Arg = MHSd->getArg(i);
1039     Init *NewArg;
1040     StringInit *ArgName = MHSd->getArgName(i);
1041 
1042     if (DagInit *Argd = dyn_cast<DagInit>(Arg))
1043       NewArg = ForeachDagApply(LHS, Argd, RHS, CurRec);
1044     else
1045       NewArg = ForeachApply(LHS, Arg, RHS, CurRec);
1046 
1047     NewArgs.push_back(std::make_pair(NewArg, ArgName));
1048     if (Arg != NewArg)
1049       Change = true;
1050   }
1051 
1052   if (Change)
1053     return DagInit::get(Val, nullptr, NewArgs);
1054   return MHSd;
1055 }
1056 
1057 // Applies RHS to all elements of MHS, using LHS as a temp variable.
1058 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1059                            Record *CurRec) {
1060   if (DagInit *MHSd = dyn_cast<DagInit>(MHS))
1061     return ForeachDagApply(LHS, MHSd, RHS, CurRec);
1062 
1063   if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) {
1064     SmallVector<Init *, 8> NewList(MHSl->begin(), MHSl->end());
1065 
1066     for (Init *&Item : NewList) {
1067       Init *NewItem = ForeachApply(LHS, Item, RHS, CurRec);
1068       if (NewItem != Item)
1069         Item = NewItem;
1070     }
1071     return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
1072   }
1073 
1074   return nullptr;
1075 }
1076 
1077 Init *TernOpInit::Fold(Record *CurRec) const {
1078   switch (getOpcode()) {
1079   case SUBST: {
1080     DefInit *LHSd = dyn_cast<DefInit>(LHS);
1081     VarInit *LHSv = dyn_cast<VarInit>(LHS);
1082     StringInit *LHSs = dyn_cast<StringInit>(LHS);
1083 
1084     DefInit *MHSd = dyn_cast<DefInit>(MHS);
1085     VarInit *MHSv = dyn_cast<VarInit>(MHS);
1086     StringInit *MHSs = dyn_cast<StringInit>(MHS);
1087 
1088     DefInit *RHSd = dyn_cast<DefInit>(RHS);
1089     VarInit *RHSv = dyn_cast<VarInit>(RHS);
1090     StringInit *RHSs = dyn_cast<StringInit>(RHS);
1091 
1092     if (LHSd && MHSd && RHSd) {
1093       Record *Val = RHSd->getDef();
1094       if (LHSd->getAsString() == RHSd->getAsString())
1095         Val = MHSd->getDef();
1096       return DefInit::get(Val);
1097     }
1098     if (LHSv && MHSv && RHSv) {
1099       std::string Val = RHSv->getName();
1100       if (LHSv->getAsString() == RHSv->getAsString())
1101         Val = MHSv->getName();
1102       return VarInit::get(Val, getType());
1103     }
1104     if (LHSs && MHSs && RHSs) {
1105       std::string Val = RHSs->getValue();
1106 
1107       std::string::size_type found;
1108       std::string::size_type idx = 0;
1109       while (true) {
1110         found = Val.find(LHSs->getValue(), idx);
1111         if (found == std::string::npos)
1112           break;
1113         Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1114         idx = found + MHSs->getValue().size();
1115       }
1116 
1117       return StringInit::get(Val);
1118     }
1119     break;
1120   }
1121 
1122   case FOREACH: {
1123     if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(), CurRec))
1124       return Result;
1125     break;
1126   }
1127 
1128   case IF: {
1129     if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
1130                             LHS->convertInitializerTo(IntRecTy::get()))) {
1131       if (LHSi->getValue())
1132         return MHS;
1133       return RHS;
1134     }
1135     break;
1136   }
1137 
1138   case DAG: {
1139     ListInit *MHSl = dyn_cast<ListInit>(MHS);
1140     ListInit *RHSl = dyn_cast<ListInit>(RHS);
1141     bool MHSok = MHSl || isa<UnsetInit>(MHS);
1142     bool RHSok = RHSl || isa<UnsetInit>(RHS);
1143 
1144     if (isa<UnsetInit>(MHS) && isa<UnsetInit>(RHS))
1145       break; // Typically prevented by the parser, but might happen with template args
1146 
1147     if (MHSok && RHSok && (!MHSl || !RHSl || MHSl->size() == RHSl->size())) {
1148       SmallVector<std::pair<Init *, StringInit *>, 8> Children;
1149       unsigned Size = MHSl ? MHSl->size() : RHSl->size();
1150       for (unsigned i = 0; i != Size; ++i) {
1151         Init *Node = MHSl ? MHSl->getElement(i) : UnsetInit::get();
1152         Init *Name = RHSl ? RHSl->getElement(i) : UnsetInit::get();
1153         if (!isa<StringInit>(Name) && !isa<UnsetInit>(Name))
1154           return const_cast<TernOpInit *>(this);
1155         Children.emplace_back(Node, dyn_cast<StringInit>(Name));
1156       }
1157       return DagInit::get(LHS, nullptr, Children);
1158     }
1159     break;
1160   }
1161   }
1162 
1163   return const_cast<TernOpInit *>(this);
1164 }
1165 
1166 Init *TernOpInit::resolveReferences(Resolver &R) const {
1167   Init *lhs = LHS->resolveReferences(R);
1168 
1169   if (getOpcode() == IF && lhs != LHS) {
1170     if (IntInit *Value = dyn_cast_or_null<IntInit>(
1171                              lhs->convertInitializerTo(IntRecTy::get()))) {
1172       // Short-circuit
1173       if (Value->getValue())
1174         return MHS->resolveReferences(R);
1175       return RHS->resolveReferences(R);
1176     }
1177   }
1178 
1179   Init *mhs = MHS->resolveReferences(R);
1180   Init *rhs;
1181 
1182   if (getOpcode() == FOREACH) {
1183     ShadowResolver SR(R);
1184     SR.addShadow(lhs);
1185     rhs = RHS->resolveReferences(SR);
1186   } else {
1187     rhs = RHS->resolveReferences(R);
1188   }
1189 
1190   if (LHS != lhs || MHS != mhs || RHS != rhs)
1191     return (TernOpInit::get(getOpcode(), lhs, mhs, rhs, getType()))
1192         ->Fold(R.getCurrentRecord());
1193   return const_cast<TernOpInit *>(this);
1194 }
1195 
1196 std::string TernOpInit::getAsString() const {
1197   std::string Result;
1198   switch (getOpcode()) {
1199   case SUBST: Result = "!subst"; break;
1200   case FOREACH: Result = "!foreach"; break;
1201   case IF: Result = "!if"; break;
1202   case DAG: Result = "!dag"; break;
1203   }
1204   return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", " +
1205          RHS->getAsString() + ")";
1206 }
1207 
1208 static void ProfileFoldOpInit(FoldingSetNodeID &ID, Init *A, Init *B,
1209                               Init *Start, Init *List, Init *Expr,
1210                               RecTy *Type) {
1211   ID.AddPointer(Start);
1212   ID.AddPointer(List);
1213   ID.AddPointer(A);
1214   ID.AddPointer(B);
1215   ID.AddPointer(Expr);
1216   ID.AddPointer(Type);
1217 }
1218 
1219 FoldOpInit *FoldOpInit::get(Init *Start, Init *List, Init *A, Init *B,
1220                             Init *Expr, RecTy *Type) {
1221   static FoldingSet<FoldOpInit> ThePool;
1222 
1223   FoldingSetNodeID ID;
1224   ProfileFoldOpInit(ID, Start, List, A, B, Expr, Type);
1225 
1226   void *IP = nullptr;
1227   if (FoldOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1228     return I;
1229 
1230   FoldOpInit *I = new (Allocator) FoldOpInit(Start, List, A, B, Expr, Type);
1231   ThePool.InsertNode(I, IP);
1232   return I;
1233 }
1234 
1235 void FoldOpInit::Profile(FoldingSetNodeID &ID) const {
1236   ProfileFoldOpInit(ID, Start, List, A, B, Expr, getType());
1237 }
1238 
1239 Init *FoldOpInit::Fold(Record *CurRec) const {
1240   if (ListInit *LI = dyn_cast<ListInit>(List)) {
1241     Init *Accum = Start;
1242     for (Init *Elt : *LI) {
1243       MapResolver R(CurRec);
1244       R.set(A, Accum);
1245       R.set(B, Elt);
1246       Accum = Expr->resolveReferences(R);
1247     }
1248     return Accum;
1249   }
1250   return const_cast<FoldOpInit *>(this);
1251 }
1252 
1253 Init *FoldOpInit::resolveReferences(Resolver &R) const {
1254   Init *NewStart = Start->resolveReferences(R);
1255   Init *NewList = List->resolveReferences(R);
1256   ShadowResolver SR(R);
1257   SR.addShadow(A);
1258   SR.addShadow(B);
1259   Init *NewExpr = Expr->resolveReferences(SR);
1260 
1261   if (Start == NewStart && List == NewList && Expr == NewExpr)
1262     return const_cast<FoldOpInit *>(this);
1263 
1264   return get(NewStart, NewList, A, B, NewExpr, getType())
1265       ->Fold(R.getCurrentRecord());
1266 }
1267 
1268 Init *FoldOpInit::getBit(unsigned Bit) const {
1269   return VarBitInit::get(const_cast<FoldOpInit *>(this), Bit);
1270 }
1271 
1272 std::string FoldOpInit::getAsString() const {
1273   return (Twine("!foldl(") + Start->getAsString() + ", " + List->getAsString() +
1274           ", " + A->getAsUnquotedString() + ", " + B->getAsUnquotedString() +
1275           ", " + Expr->getAsString() + ")")
1276       .str();
1277 }
1278 
1279 static void ProfileIsAOpInit(FoldingSetNodeID &ID, RecTy *CheckType,
1280                              Init *Expr) {
1281   ID.AddPointer(CheckType);
1282   ID.AddPointer(Expr);
1283 }
1284 
1285 IsAOpInit *IsAOpInit::get(RecTy *CheckType, Init *Expr) {
1286   static FoldingSet<IsAOpInit> ThePool;
1287 
1288   FoldingSetNodeID ID;
1289   ProfileIsAOpInit(ID, CheckType, Expr);
1290 
1291   void *IP = nullptr;
1292   if (IsAOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1293     return I;
1294 
1295   IsAOpInit *I = new (Allocator) IsAOpInit(CheckType, Expr);
1296   ThePool.InsertNode(I, IP);
1297   return I;
1298 }
1299 
1300 void IsAOpInit::Profile(FoldingSetNodeID &ID) const {
1301   ProfileIsAOpInit(ID, CheckType, Expr);
1302 }
1303 
1304 Init *IsAOpInit::Fold() const {
1305   if (TypedInit *TI = dyn_cast<TypedInit>(Expr)) {
1306     // Is the expression type known to be (a subclass of) the desired type?
1307     if (TI->getType()->typeIsConvertibleTo(CheckType))
1308       return IntInit::get(1);
1309 
1310     if (isa<RecordRecTy>(CheckType)) {
1311       // If the target type is not a subclass of the expression type, or if
1312       // the expression has fully resolved to a record, we know that it can't
1313       // be of the required type.
1314       if (!CheckType->typeIsConvertibleTo(TI->getType()) || isa<DefInit>(Expr))
1315         return IntInit::get(0);
1316     } else {
1317       // We treat non-record types as not castable.
1318       return IntInit::get(0);
1319     }
1320   }
1321   return const_cast<IsAOpInit *>(this);
1322 }
1323 
1324 Init *IsAOpInit::resolveReferences(Resolver &R) const {
1325   Init *NewExpr = Expr->resolveReferences(R);
1326   if (Expr != NewExpr)
1327     return get(CheckType, NewExpr)->Fold();
1328   return const_cast<IsAOpInit *>(this);
1329 }
1330 
1331 Init *IsAOpInit::getBit(unsigned Bit) const {
1332   return VarBitInit::get(const_cast<IsAOpInit *>(this), Bit);
1333 }
1334 
1335 std::string IsAOpInit::getAsString() const {
1336   return (Twine("!isa<") + CheckType->getAsString() + ">(" +
1337           Expr->getAsString() + ")")
1338       .str();
1339 }
1340 
1341 RecTy *TypedInit::getFieldType(StringInit *FieldName) const {
1342   if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType())) {
1343     for (Record *Rec : RecordType->getClasses()) {
1344       if (RecordVal *Field = Rec->getValue(FieldName))
1345         return Field->getType();
1346     }
1347   }
1348   return nullptr;
1349 }
1350 
1351 Init *
1352 TypedInit::convertInitializerTo(RecTy *Ty) const {
1353   if (getType() == Ty || getType()->typeIsA(Ty))
1354     return const_cast<TypedInit *>(this);
1355 
1356   if (isa<BitRecTy>(getType()) && isa<BitsRecTy>(Ty) &&
1357       cast<BitsRecTy>(Ty)->getNumBits() == 1)
1358     return BitsInit::get({const_cast<TypedInit *>(this)});
1359 
1360   return nullptr;
1361 }
1362 
1363 Init *TypedInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
1364   BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1365   if (!T) return nullptr;  // Cannot subscript a non-bits variable.
1366   unsigned NumBits = T->getNumBits();
1367 
1368   SmallVector<Init *, 16> NewBits;
1369   NewBits.reserve(Bits.size());
1370   for (unsigned Bit : Bits) {
1371     if (Bit >= NumBits)
1372       return nullptr;
1373 
1374     NewBits.push_back(VarBitInit::get(const_cast<TypedInit *>(this), Bit));
1375   }
1376   return BitsInit::get(NewBits);
1377 }
1378 
1379 Init *TypedInit::getCastTo(RecTy *Ty) const {
1380   // Handle the common case quickly
1381   if (getType() == Ty || getType()->typeIsA(Ty))
1382     return const_cast<TypedInit *>(this);
1383 
1384   if (Init *Converted = convertInitializerTo(Ty)) {
1385     assert(!isa<TypedInit>(Converted) ||
1386            cast<TypedInit>(Converted)->getType()->typeIsA(Ty));
1387     return Converted;
1388   }
1389 
1390   if (!getType()->typeIsConvertibleTo(Ty))
1391     return nullptr;
1392 
1393   return UnOpInit::get(UnOpInit::CAST, const_cast<TypedInit *>(this), Ty)
1394       ->Fold(nullptr);
1395 }
1396 
1397 Init *TypedInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
1398   ListRecTy *T = dyn_cast<ListRecTy>(getType());
1399   if (!T) return nullptr;  // Cannot subscript a non-list variable.
1400 
1401   if (Elements.size() == 1)
1402     return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1403 
1404   SmallVector<Init*, 8> ListInits;
1405   ListInits.reserve(Elements.size());
1406   for (unsigned Element : Elements)
1407     ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1408                                                 Element));
1409   return ListInit::get(ListInits, T->getElementType());
1410 }
1411 
1412 
1413 VarInit *VarInit::get(StringRef VN, RecTy *T) {
1414   Init *Value = StringInit::get(VN);
1415   return VarInit::get(Value, T);
1416 }
1417 
1418 VarInit *VarInit::get(Init *VN, RecTy *T) {
1419   using Key = std::pair<RecTy *, Init *>;
1420   static DenseMap<Key, VarInit*> ThePool;
1421 
1422   Key TheKey(std::make_pair(T, VN));
1423 
1424   VarInit *&I = ThePool[TheKey];
1425   if (!I)
1426     I = new(Allocator) VarInit(VN, T);
1427   return I;
1428 }
1429 
1430 StringRef VarInit::getName() const {
1431   StringInit *NameString = cast<StringInit>(getNameInit());
1432   return NameString->getValue();
1433 }
1434 
1435 Init *VarInit::getBit(unsigned Bit) const {
1436   if (getType() == BitRecTy::get())
1437     return const_cast<VarInit*>(this);
1438   return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1439 }
1440 
1441 Init *VarInit::resolveReferences(Resolver &R) const {
1442   if (Init *Val = R.resolve(VarName))
1443     return Val;
1444   return const_cast<VarInit *>(this);
1445 }
1446 
1447 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1448   using Key = std::pair<TypedInit *, unsigned>;
1449   static DenseMap<Key, VarBitInit*> ThePool;
1450 
1451   Key TheKey(std::make_pair(T, B));
1452 
1453   VarBitInit *&I = ThePool[TheKey];
1454   if (!I)
1455     I = new(Allocator) VarBitInit(T, B);
1456   return I;
1457 }
1458 
1459 std::string VarBitInit::getAsString() const {
1460   return TI->getAsString() + "{" + utostr(Bit) + "}";
1461 }
1462 
1463 Init *VarBitInit::resolveReferences(Resolver &R) const {
1464   Init *I = TI->resolveReferences(R);
1465   if (TI != I)
1466     return I->getBit(getBitNum());
1467 
1468   return const_cast<VarBitInit*>(this);
1469 }
1470 
1471 VarListElementInit *VarListElementInit::get(TypedInit *T,
1472                                             unsigned E) {
1473   using Key = std::pair<TypedInit *, unsigned>;
1474   static DenseMap<Key, VarListElementInit*> ThePool;
1475 
1476   Key TheKey(std::make_pair(T, E));
1477 
1478   VarListElementInit *&I = ThePool[TheKey];
1479   if (!I) I = new(Allocator) VarListElementInit(T, E);
1480   return I;
1481 }
1482 
1483 std::string VarListElementInit::getAsString() const {
1484   return TI->getAsString() + "[" + utostr(Element) + "]";
1485 }
1486 
1487 Init *VarListElementInit::resolveReferences(Resolver &R) const {
1488   Init *NewTI = TI->resolveReferences(R);
1489   if (ListInit *List = dyn_cast<ListInit>(NewTI)) {
1490     // Leave out-of-bounds array references as-is. This can happen without
1491     // being an error, e.g. in the untaken "branch" of an !if expression.
1492     if (getElementNum() < List->size())
1493       return List->getElement(getElementNum());
1494   }
1495   if (NewTI != TI && isa<TypedInit>(NewTI))
1496     return VarListElementInit::get(cast<TypedInit>(NewTI), getElementNum());
1497   return const_cast<VarListElementInit *>(this);
1498 }
1499 
1500 Init *VarListElementInit::getBit(unsigned Bit) const {
1501   if (getType() == BitRecTy::get())
1502     return const_cast<VarListElementInit*>(this);
1503   return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1504 }
1505 
1506 DefInit::DefInit(Record *D)
1507     : TypedInit(IK_DefInit, D->getType()), Def(D) {}
1508 
1509 DefInit *DefInit::get(Record *R) {
1510   return R->getDefInit();
1511 }
1512 
1513 Init *DefInit::convertInitializerTo(RecTy *Ty) const {
1514   if (auto *RRT = dyn_cast<RecordRecTy>(Ty))
1515     if (getType()->typeIsConvertibleTo(RRT))
1516       return const_cast<DefInit *>(this);
1517   return nullptr;
1518 }
1519 
1520 RecTy *DefInit::getFieldType(StringInit *FieldName) const {
1521   if (const RecordVal *RV = Def->getValue(FieldName))
1522     return RV->getType();
1523   return nullptr;
1524 }
1525 
1526 std::string DefInit::getAsString() const {
1527   return Def->getName();
1528 }
1529 
1530 static void ProfileVarDefInit(FoldingSetNodeID &ID,
1531                               Record *Class,
1532                               ArrayRef<Init *> Args) {
1533   ID.AddInteger(Args.size());
1534   ID.AddPointer(Class);
1535 
1536   for (Init *I : Args)
1537     ID.AddPointer(I);
1538 }
1539 
1540 VarDefInit *VarDefInit::get(Record *Class, ArrayRef<Init *> Args) {
1541   static FoldingSet<VarDefInit> ThePool;
1542 
1543   FoldingSetNodeID ID;
1544   ProfileVarDefInit(ID, Class, Args);
1545 
1546   void *IP = nullptr;
1547   if (VarDefInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1548     return I;
1549 
1550   void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Args.size()),
1551                                  alignof(VarDefInit));
1552   VarDefInit *I = new(Mem) VarDefInit(Class, Args.size());
1553   std::uninitialized_copy(Args.begin(), Args.end(),
1554                           I->getTrailingObjects<Init *>());
1555   ThePool.InsertNode(I, IP);
1556   return I;
1557 }
1558 
1559 void VarDefInit::Profile(FoldingSetNodeID &ID) const {
1560   ProfileVarDefInit(ID, Class, args());
1561 }
1562 
1563 DefInit *VarDefInit::instantiate() {
1564   if (!Def) {
1565     RecordKeeper &Records = Class->getRecords();
1566     auto NewRecOwner = make_unique<Record>(Records.getNewAnonymousName(),
1567                                            Class->getLoc(), Records,
1568                                            /*IsAnonymous=*/true);
1569     Record *NewRec = NewRecOwner.get();
1570 
1571     // Copy values from class to instance
1572     for (const RecordVal &Val : Class->getValues()) {
1573       if (Val.getName() != "NAME")
1574         NewRec->addValue(Val);
1575     }
1576 
1577     // Substitute and resolve template arguments
1578     ArrayRef<Init *> TArgs = Class->getTemplateArgs();
1579     MapResolver R(NewRec);
1580 
1581     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1582       if (i < args_size())
1583         R.set(TArgs[i], getArg(i));
1584       else
1585         R.set(TArgs[i], NewRec->getValue(TArgs[i])->getValue());
1586 
1587       NewRec->removeValue(TArgs[i]);
1588     }
1589 
1590     NewRec->resolveReferences(R);
1591 
1592     // Add superclasses.
1593     ArrayRef<std::pair<Record *, SMRange>> SCs = Class->getSuperClasses();
1594     for (const auto &SCPair : SCs)
1595       NewRec->addSuperClass(SCPair.first, SCPair.second);
1596 
1597     NewRec->addSuperClass(Class,
1598                           SMRange(Class->getLoc().back(),
1599                                   Class->getLoc().back()));
1600 
1601     // Resolve internal references and store in record keeper
1602     NewRec->resolveReferences();
1603     Records.addDef(std::move(NewRecOwner));
1604 
1605     Def = DefInit::get(NewRec);
1606   }
1607 
1608   return Def;
1609 }
1610 
1611 Init *VarDefInit::resolveReferences(Resolver &R) const {
1612   TrackUnresolvedResolver UR(&R);
1613   bool Changed = false;
1614   SmallVector<Init *, 8> NewArgs;
1615   NewArgs.reserve(args_size());
1616 
1617   for (Init *Arg : args()) {
1618     Init *NewArg = Arg->resolveReferences(UR);
1619     NewArgs.push_back(NewArg);
1620     Changed |= NewArg != Arg;
1621   }
1622 
1623   if (Changed) {
1624     auto New = VarDefInit::get(Class, NewArgs);
1625     if (!UR.foundUnresolved())
1626       return New->instantiate();
1627     return New;
1628   }
1629   return const_cast<VarDefInit *>(this);
1630 }
1631 
1632 Init *VarDefInit::Fold() const {
1633   if (Def)
1634     return Def;
1635 
1636   TrackUnresolvedResolver R;
1637   for (Init *Arg : args())
1638     Arg->resolveReferences(R);
1639 
1640   if (!R.foundUnresolved())
1641     return const_cast<VarDefInit *>(this)->instantiate();
1642   return const_cast<VarDefInit *>(this);
1643 }
1644 
1645 std::string VarDefInit::getAsString() const {
1646   std::string Result = Class->getNameInitAsString() + "<";
1647   const char *sep = "";
1648   for (Init *Arg : args()) {
1649     Result += sep;
1650     sep = ", ";
1651     Result += Arg->getAsString();
1652   }
1653   return Result + ">";
1654 }
1655 
1656 FieldInit *FieldInit::get(Init *R, StringInit *FN) {
1657   using Key = std::pair<Init *, StringInit *>;
1658   static DenseMap<Key, FieldInit*> ThePool;
1659 
1660   Key TheKey(std::make_pair(R, FN));
1661 
1662   FieldInit *&I = ThePool[TheKey];
1663   if (!I) I = new(Allocator) FieldInit(R, FN);
1664   return I;
1665 }
1666 
1667 Init *FieldInit::getBit(unsigned Bit) const {
1668   if (getType() == BitRecTy::get())
1669     return const_cast<FieldInit*>(this);
1670   return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1671 }
1672 
1673 Init *FieldInit::resolveReferences(Resolver &R) const {
1674   Init *NewRec = Rec->resolveReferences(R);
1675   if (NewRec != Rec)
1676     return FieldInit::get(NewRec, FieldName)->Fold(R.getCurrentRecord());
1677   return const_cast<FieldInit *>(this);
1678 }
1679 
1680 Init *FieldInit::Fold(Record *CurRec) const {
1681   if (DefInit *DI = dyn_cast<DefInit>(Rec)) {
1682     Record *Def = DI->getDef();
1683     if (Def == CurRec)
1684       PrintFatalError(CurRec->getLoc(),
1685                       Twine("Attempting to access field '") +
1686                       FieldName->getAsUnquotedString() + "' of '" +
1687                       Rec->getAsString() + "' is a forbidden self-reference");
1688     Init *FieldVal = Def->getValue(FieldName)->getValue();
1689     if (FieldVal->isComplete())
1690       return FieldVal;
1691   }
1692   return const_cast<FieldInit *>(this);
1693 }
1694 
1695 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, StringInit *VN,
1696                            ArrayRef<Init *> ArgRange,
1697                            ArrayRef<StringInit *> NameRange) {
1698   ID.AddPointer(V);
1699   ID.AddPointer(VN);
1700 
1701   ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1702   ArrayRef<StringInit *>::iterator Name = NameRange.begin();
1703   while (Arg != ArgRange.end()) {
1704     assert(Name != NameRange.end() && "Arg name underflow!");
1705     ID.AddPointer(*Arg++);
1706     ID.AddPointer(*Name++);
1707   }
1708   assert(Name == NameRange.end() && "Arg name overflow!");
1709 }
1710 
1711 DagInit *
1712 DagInit::get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
1713              ArrayRef<StringInit *> NameRange) {
1714   static FoldingSet<DagInit> ThePool;
1715 
1716   FoldingSetNodeID ID;
1717   ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1718 
1719   void *IP = nullptr;
1720   if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1721     return I;
1722 
1723   void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *, StringInit *>(ArgRange.size(), NameRange.size()), alignof(BitsInit));
1724   DagInit *I = new(Mem) DagInit(V, VN, ArgRange.size(), NameRange.size());
1725   std::uninitialized_copy(ArgRange.begin(), ArgRange.end(),
1726                           I->getTrailingObjects<Init *>());
1727   std::uninitialized_copy(NameRange.begin(), NameRange.end(),
1728                           I->getTrailingObjects<StringInit *>());
1729   ThePool.InsertNode(I, IP);
1730   return I;
1731 }
1732 
1733 DagInit *
1734 DagInit::get(Init *V, StringInit *VN,
1735              ArrayRef<std::pair<Init*, StringInit*>> args) {
1736   SmallVector<Init *, 8> Args;
1737   SmallVector<StringInit *, 8> Names;
1738 
1739   for (const auto &Arg : args) {
1740     Args.push_back(Arg.first);
1741     Names.push_back(Arg.second);
1742   }
1743 
1744   return DagInit::get(V, VN, Args, Names);
1745 }
1746 
1747 void DagInit::Profile(FoldingSetNodeID &ID) const {
1748   ProfileDagInit(ID, Val, ValName, makeArrayRef(getTrailingObjects<Init *>(), NumArgs), makeArrayRef(getTrailingObjects<StringInit *>(), NumArgNames));
1749 }
1750 
1751 Init *DagInit::resolveReferences(Resolver &R) const {
1752   SmallVector<Init*, 8> NewArgs;
1753   NewArgs.reserve(arg_size());
1754   bool ArgsChanged = false;
1755   for (const Init *Arg : getArgs()) {
1756     Init *NewArg = Arg->resolveReferences(R);
1757     NewArgs.push_back(NewArg);
1758     ArgsChanged |= NewArg != Arg;
1759   }
1760 
1761   Init *Op = Val->resolveReferences(R);
1762   if (Op != Val || ArgsChanged)
1763     return DagInit::get(Op, ValName, NewArgs, getArgNames());
1764 
1765   return const_cast<DagInit *>(this);
1766 }
1767 
1768 bool DagInit::isConcrete() const {
1769   if (!Val->isConcrete())
1770     return false;
1771   for (const Init *Elt : getArgs()) {
1772     if (!Elt->isConcrete())
1773       return false;
1774   }
1775   return true;
1776 }
1777 
1778 std::string DagInit::getAsString() const {
1779   std::string Result = "(" + Val->getAsString();
1780   if (ValName)
1781     Result += ":" + ValName->getAsUnquotedString();
1782   if (!arg_empty()) {
1783     Result += " " + getArg(0)->getAsString();
1784     if (getArgName(0)) Result += ":$" + getArgName(0)->getAsUnquotedString();
1785     for (unsigned i = 1, e = getNumArgs(); i != e; ++i) {
1786       Result += ", " + getArg(i)->getAsString();
1787       if (getArgName(i)) Result += ":$" + getArgName(i)->getAsUnquotedString();
1788     }
1789   }
1790   return Result + ")";
1791 }
1792 
1793 //===----------------------------------------------------------------------===//
1794 //    Other implementations
1795 //===----------------------------------------------------------------------===//
1796 
1797 RecordVal::RecordVal(Init *N, RecTy *T, bool P)
1798   : Name(N), TyAndPrefix(T, P) {
1799   setValue(UnsetInit::get());
1800   assert(Value && "Cannot create unset value for current type!");
1801 }
1802 
1803 StringRef RecordVal::getName() const {
1804   return cast<StringInit>(getNameInit())->getValue();
1805 }
1806 
1807 bool RecordVal::setValue(Init *V) {
1808   if (V) {
1809     Value = V->getCastTo(getType());
1810     if (Value) {
1811       assert(!isa<TypedInit>(Value) ||
1812              cast<TypedInit>(Value)->getType()->typeIsA(getType()));
1813       if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {
1814         if (!isa<BitsInit>(Value)) {
1815           SmallVector<Init *, 64> Bits;
1816           Bits.reserve(BTy->getNumBits());
1817           for (unsigned i = 0, e = BTy->getNumBits(); i < e; ++i)
1818             Bits.push_back(Value->getBit(i));
1819           Value = BitsInit::get(Bits);
1820         }
1821       }
1822     }
1823     return Value == nullptr;
1824   }
1825   Value = nullptr;
1826   return false;
1827 }
1828 
1829 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1830 LLVM_DUMP_METHOD void RecordVal::dump() const { errs() << *this; }
1831 #endif
1832 
1833 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1834   if (getPrefix()) OS << "field ";
1835   OS << *getType() << " " << getNameInitAsString();
1836 
1837   if (getValue())
1838     OS << " = " << *getValue();
1839 
1840   if (PrintSem) OS << ";\n";
1841 }
1842 
1843 unsigned Record::LastID = 0;
1844 
1845 void Record::init() {
1846   checkName();
1847 
1848   // Every record potentially has a def at the top.  This value is
1849   // replaced with the top-level def name at instantiation time.
1850   addValue(RecordVal(StringInit::get("NAME"), StringRecTy::get(), false));
1851 }
1852 
1853 void Record::checkName() {
1854   // Ensure the record name has string type.
1855   const TypedInit *TypedName = cast<const TypedInit>(Name);
1856   if (!isa<StringRecTy>(TypedName->getType()))
1857     PrintFatalError(getLoc(), Twine("Record name '") + Name->getAsString() +
1858                                   "' is not a string!");
1859 }
1860 
1861 RecordRecTy *Record::getType() {
1862   SmallVector<Record *, 4> DirectSCs;
1863   getDirectSuperClasses(DirectSCs);
1864   return RecordRecTy::get(DirectSCs);
1865 }
1866 
1867 DefInit *Record::getDefInit() {
1868   if (!TheInit)
1869     TheInit = new(Allocator) DefInit(this);
1870   return TheInit;
1871 }
1872 
1873 void Record::setName(Init *NewName) {
1874   Name = NewName;
1875   checkName();
1876   // DO NOT resolve record values to the name at this point because
1877   // there might be default values for arguments of this def.  Those
1878   // arguments might not have been resolved yet so we don't want to
1879   // prematurely assume values for those arguments were not passed to
1880   // this def.
1881   //
1882   // Nonetheless, it may be that some of this Record's values
1883   // reference the record name.  Indeed, the reason for having the
1884   // record name be an Init is to provide this flexibility.  The extra
1885   // resolve steps after completely instantiating defs takes care of
1886   // this.  See TGParser::ParseDef and TGParser::ParseDefm.
1887 }
1888 
1889 void Record::getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const {
1890   ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();
1891   while (!SCs.empty()) {
1892     // Superclasses are in reverse preorder, so 'back' is a direct superclass,
1893     // and its transitive superclasses are directly preceding it.
1894     Record *SC = SCs.back().first;
1895     SCs = SCs.drop_back(1 + SC->getSuperClasses().size());
1896     Classes.push_back(SC);
1897   }
1898 }
1899 
1900 void Record::resolveReferences(Resolver &R, const RecordVal *SkipVal) {
1901   for (RecordVal &Value : Values) {
1902     if (SkipVal == &Value) // Skip resolve the same field as the given one
1903       continue;
1904     if (Init *V = Value.getValue()) {
1905       Init *VR = V->resolveReferences(R);
1906       if (Value.setValue(VR)) {
1907         std::string Type;
1908         if (TypedInit *VRT = dyn_cast<TypedInit>(VR))
1909           Type =
1910               (Twine("of type '") + VRT->getType()->getAsString() + "' ").str();
1911         PrintFatalError(getLoc(), Twine("Invalid value ") + Type +
1912                                       "is found when setting '" +
1913                                       Value.getNameInitAsString() +
1914                                       "' of type '" +
1915                                       Value.getType()->getAsString() +
1916                                       "' after resolving references: " +
1917                                       VR->getAsUnquotedString() + "\n");
1918       }
1919     }
1920   }
1921   Init *OldName = getNameInit();
1922   Init *NewName = Name->resolveReferences(R);
1923   if (NewName != OldName) {
1924     // Re-register with RecordKeeper.
1925     setName(NewName);
1926   }
1927 }
1928 
1929 void Record::resolveReferences() {
1930   RecordResolver R(*this);
1931   R.setFinal(true);
1932   resolveReferences(R);
1933 }
1934 
1935 void Record::resolveReferencesTo(const RecordVal *RV) {
1936   RecordValResolver R(*this, RV);
1937   resolveReferences(R, RV);
1938 }
1939 
1940 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1941 LLVM_DUMP_METHOD void Record::dump() const { errs() << *this; }
1942 #endif
1943 
1944 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1945   OS << R.getNameInitAsString();
1946 
1947   ArrayRef<Init *> TArgs = R.getTemplateArgs();
1948   if (!TArgs.empty()) {
1949     OS << "<";
1950     bool NeedComma = false;
1951     for (const Init *TA : TArgs) {
1952       if (NeedComma) OS << ", ";
1953       NeedComma = true;
1954       const RecordVal *RV = R.getValue(TA);
1955       assert(RV && "Template argument record not found??");
1956       RV->print(OS, false);
1957     }
1958     OS << ">";
1959   }
1960 
1961   OS << " {";
1962   ArrayRef<std::pair<Record *, SMRange>> SC = R.getSuperClasses();
1963   if (!SC.empty()) {
1964     OS << "\t//";
1965     for (const auto &SuperPair : SC)
1966       OS << " " << SuperPair.first->getNameInitAsString();
1967   }
1968   OS << "\n";
1969 
1970   for (const RecordVal &Val : R.getValues())
1971     if (Val.getPrefix() && !R.isTemplateArg(Val.getNameInit()))
1972       OS << Val;
1973   for (const RecordVal &Val : R.getValues())
1974     if (!Val.getPrefix() && !R.isTemplateArg(Val.getNameInit()))
1975       OS << Val;
1976 
1977   return OS << "}\n";
1978 }
1979 
1980 Init *Record::getValueInit(StringRef FieldName) const {
1981   const RecordVal *R = getValue(FieldName);
1982   if (!R || !R->getValue())
1983     PrintFatalError(getLoc(), "Record `" + getName() +
1984       "' does not have a field named `" + FieldName + "'!\n");
1985   return R->getValue();
1986 }
1987 
1988 StringRef Record::getValueAsString(StringRef FieldName) const {
1989   const RecordVal *R = getValue(FieldName);
1990   if (!R || !R->getValue())
1991     PrintFatalError(getLoc(), "Record `" + getName() +
1992       "' does not have a field named `" + FieldName + "'!\n");
1993 
1994   if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1995     return SI->getValue();
1996   if (CodeInit *CI = dyn_cast<CodeInit>(R->getValue()))
1997     return CI->getValue();
1998 
1999   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2000     FieldName + "' does not have a string initializer!");
2001 }
2002 
2003 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
2004   const RecordVal *R = getValue(FieldName);
2005   if (!R || !R->getValue())
2006     PrintFatalError(getLoc(), "Record `" + getName() +
2007       "' does not have a field named `" + FieldName + "'!\n");
2008 
2009   if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
2010     return BI;
2011   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2012     FieldName + "' does not have a BitsInit initializer!");
2013 }
2014 
2015 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
2016   const RecordVal *R = getValue(FieldName);
2017   if (!R || !R->getValue())
2018     PrintFatalError(getLoc(), "Record `" + getName() +
2019       "' does not have a field named `" + FieldName + "'!\n");
2020 
2021   if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
2022     return LI;
2023   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2024     FieldName + "' does not have a list initializer!");
2025 }
2026 
2027 std::vector<Record*>
2028 Record::getValueAsListOfDefs(StringRef FieldName) const {
2029   ListInit *List = getValueAsListInit(FieldName);
2030   std::vector<Record*> Defs;
2031   for (Init *I : List->getValues()) {
2032     if (DefInit *DI = dyn_cast<DefInit>(I))
2033       Defs.push_back(DI->getDef());
2034     else
2035       PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2036         FieldName + "' list is not entirely DefInit!");
2037   }
2038   return Defs;
2039 }
2040 
2041 int64_t Record::getValueAsInt(StringRef FieldName) const {
2042   const RecordVal *R = getValue(FieldName);
2043   if (!R || !R->getValue())
2044     PrintFatalError(getLoc(), "Record `" + getName() +
2045       "' does not have a field named `" + FieldName + "'!\n");
2046 
2047   if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
2048     return II->getValue();
2049   PrintFatalError(getLoc(), Twine("Record `") + getName() + "', field `" +
2050                                 FieldName +
2051                                 "' does not have an int initializer: " +
2052                                 R->getValue()->getAsString());
2053 }
2054 
2055 std::vector<int64_t>
2056 Record::getValueAsListOfInts(StringRef FieldName) const {
2057   ListInit *List = getValueAsListInit(FieldName);
2058   std::vector<int64_t> Ints;
2059   for (Init *I : List->getValues()) {
2060     if (IntInit *II = dyn_cast<IntInit>(I))
2061       Ints.push_back(II->getValue());
2062     else
2063       PrintFatalError(getLoc(),
2064                       Twine("Record `") + getName() + "', field `" + FieldName +
2065                           "' does not have a list of ints initializer: " +
2066                           I->getAsString());
2067   }
2068   return Ints;
2069 }
2070 
2071 std::vector<StringRef>
2072 Record::getValueAsListOfStrings(StringRef FieldName) const {
2073   ListInit *List = getValueAsListInit(FieldName);
2074   std::vector<StringRef> Strings;
2075   for (Init *I : List->getValues()) {
2076     if (StringInit *SI = dyn_cast<StringInit>(I))
2077       Strings.push_back(SI->getValue());
2078     else
2079       PrintFatalError(getLoc(),
2080                       Twine("Record `") + getName() + "', field `" + FieldName +
2081                           "' does not have a list of strings initializer: " +
2082                           I->getAsString());
2083   }
2084   return Strings;
2085 }
2086 
2087 Record *Record::getValueAsDef(StringRef FieldName) const {
2088   const RecordVal *R = getValue(FieldName);
2089   if (!R || !R->getValue())
2090     PrintFatalError(getLoc(), "Record `" + getName() +
2091       "' does not have a field named `" + FieldName + "'!\n");
2092 
2093   if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
2094     return DI->getDef();
2095   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2096     FieldName + "' does not have a def initializer!");
2097 }
2098 
2099 bool Record::getValueAsBit(StringRef FieldName) const {
2100   const RecordVal *R = getValue(FieldName);
2101   if (!R || !R->getValue())
2102     PrintFatalError(getLoc(), "Record `" + getName() +
2103       "' does not have a field named `" + FieldName + "'!\n");
2104 
2105   if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
2106     return BI->getValue();
2107   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2108     FieldName + "' does not have a bit initializer!");
2109 }
2110 
2111 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
2112   const RecordVal *R = getValue(FieldName);
2113   if (!R || !R->getValue())
2114     PrintFatalError(getLoc(), "Record `" + getName() +
2115       "' does not have a field named `" + FieldName.str() + "'!\n");
2116 
2117   if (isa<UnsetInit>(R->getValue())) {
2118     Unset = true;
2119     return false;
2120   }
2121   Unset = false;
2122   if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
2123     return BI->getValue();
2124   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2125     FieldName + "' does not have a bit initializer!");
2126 }
2127 
2128 DagInit *Record::getValueAsDag(StringRef FieldName) const {
2129   const RecordVal *R = getValue(FieldName);
2130   if (!R || !R->getValue())
2131     PrintFatalError(getLoc(), "Record `" + getName() +
2132       "' does not have a field named `" + FieldName + "'!\n");
2133 
2134   if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
2135     return DI;
2136   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2137     FieldName + "' does not have a dag initializer!");
2138 }
2139 
2140 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2141 LLVM_DUMP_METHOD void MultiClass::dump() const {
2142   errs() << "Record:\n";
2143   Rec.dump();
2144 
2145   errs() << "Defs:\n";
2146   for (const auto &Proto : DefPrototypes)
2147     Proto->dump();
2148 }
2149 
2150 LLVM_DUMP_METHOD void RecordKeeper::dump() const { errs() << *this; }
2151 #endif
2152 
2153 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
2154   OS << "------------- Classes -----------------\n";
2155   for (const auto &C : RK.getClasses())
2156     OS << "class " << *C.second;
2157 
2158   OS << "------------- Defs -----------------\n";
2159   for (const auto &D : RK.getDefs())
2160     OS << "def " << *D.second;
2161   return OS;
2162 }
2163 
2164 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
2165 /// an identifier.
2166 Init *RecordKeeper::getNewAnonymousName() {
2167   return StringInit::get("anonymous_" + utostr(AnonCounter++));
2168 }
2169 
2170 std::vector<Record *>
2171 RecordKeeper::getAllDerivedDefinitions(StringRef ClassName) const {
2172   Record *Class = getClass(ClassName);
2173   if (!Class)
2174     PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
2175 
2176   std::vector<Record*> Defs;
2177   for (const auto &D : getDefs())
2178     if (D.second->isSubClassOf(Class))
2179       Defs.push_back(D.second.get());
2180 
2181   return Defs;
2182 }
2183 
2184 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2185                         Init *Name, StringRef Scoper) {
2186   Init *NewName =
2187       BinOpInit::getStrConcat(CurRec.getNameInit(), StringInit::get(Scoper));
2188   NewName = BinOpInit::getStrConcat(NewName, Name);
2189   if (CurMultiClass && Scoper != "::") {
2190     Init *Prefix = BinOpInit::getStrConcat(CurMultiClass->Rec.getNameInit(),
2191                                            StringInit::get("::"));
2192     NewName = BinOpInit::getStrConcat(Prefix, NewName);
2193   }
2194 
2195   if (BinOpInit *BinOp = dyn_cast<BinOpInit>(NewName))
2196     NewName = BinOp->Fold(&CurRec);
2197   return NewName;
2198 }
2199 
2200 Init *MapResolver::resolve(Init *VarName) {
2201   auto It = Map.find(VarName);
2202   if (It == Map.end())
2203     return nullptr;
2204 
2205   Init *I = It->second.V;
2206 
2207   if (!It->second.Resolved && Map.size() > 1) {
2208     // Resolve mutual references among the mapped variables, but prevent
2209     // infinite recursion.
2210     Map.erase(It);
2211     I = I->resolveReferences(*this);
2212     Map[VarName] = {I, true};
2213   }
2214 
2215   return I;
2216 }
2217 
2218 Init *RecordResolver::resolve(Init *VarName) {
2219   Init *Val = Cache.lookup(VarName);
2220   if (Val)
2221     return Val;
2222 
2223   for (Init *S : Stack) {
2224     if (S == VarName)
2225       return nullptr; // prevent infinite recursion
2226   }
2227 
2228   if (RecordVal *RV = getCurrentRecord()->getValue(VarName)) {
2229     if (!isa<UnsetInit>(RV->getValue())) {
2230       Val = RV->getValue();
2231       Stack.push_back(VarName);
2232       Val = Val->resolveReferences(*this);
2233       Stack.pop_back();
2234     }
2235   }
2236 
2237   Cache[VarName] = Val;
2238   return Val;
2239 }
2240 
2241 Init *TrackUnresolvedResolver::resolve(Init *VarName) {
2242   Init *I = nullptr;
2243 
2244   if (R) {
2245     I = R->resolve(VarName);
2246     if (I && !FoundUnresolved) {
2247       // Do not recurse into the resolved initializer, as that would change
2248       // the behavior of the resolver we're delegating, but do check to see
2249       // if there are unresolved variables remaining.
2250       TrackUnresolvedResolver Sub;
2251       I->resolveReferences(Sub);
2252       FoundUnresolved |= Sub.FoundUnresolved;
2253     }
2254   }
2255 
2256   if (!I)
2257     FoundUnresolved = true;
2258   return I;
2259 }
2260