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