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<" + ElementTy->getAsString() + ">";
132 }
133 
134 bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
135   if (const auto *ListTy = dyn_cast<ListRecTy>(RHS))
136     return ElementTy->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       assert(CachedBitVarResolved && "Unresolved bitvar reference");
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 NOT:
765     if (IntInit *LHSi =
766             dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get())))
767       return IntInit::get(LHSi->getValue() ? 0 : 1);
768     break;
769 
770   case HEAD:
771     if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
772       assert(!LHSl->empty() && "Empty list in head");
773       return LHSl->getElement(0);
774     }
775     break;
776 
777   case TAIL:
778     if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
779       assert(!LHSl->empty() && "Empty list in tail");
780       // Note the +1.  We can't just pass the result of getValues()
781       // directly.
782       return ListInit::get(LHSl->getValues().slice(1), LHSl->getElementType());
783     }
784     break;
785 
786   case SIZE:
787     if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
788       return IntInit::get(LHSl->size());
789     if (DagInit *LHSd = dyn_cast<DagInit>(LHS))
790       return IntInit::get(LHSd->arg_size());
791     if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
792       return IntInit::get(LHSs->getValue().size());
793     break;
794 
795   case EMPTY:
796     if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
797       return IntInit::get(LHSl->empty());
798     if (DagInit *LHSd = dyn_cast<DagInit>(LHS))
799       return IntInit::get(LHSd->arg_empty());
800     if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
801       return IntInit::get(LHSs->getValue().empty());
802     break;
803 
804   case GETDAGOP:
805     if (DagInit *Dag = dyn_cast<DagInit>(LHS)) {
806       DefInit *DI = DefInit::get(Dag->getOperatorAsDef({}));
807       if (!DI->getType()->typeIsA(getType())) {
808         PrintFatalError(CurRec->getLoc(),
809                         Twine("Expected type '") +
810                         getType()->getAsString() + "', got '" +
811                         DI->getType()->getAsString() + "' in: " +
812                         getAsString() + "\n");
813       } else {
814         return DI;
815       }
816     }
817     break;
818   }
819   return const_cast<UnOpInit *>(this);
820 }
821 
822 Init *UnOpInit::resolveReferences(Resolver &R) const {
823   Init *lhs = LHS->resolveReferences(R);
824 
825   if (LHS != lhs || (R.isFinal() && getOpcode() == CAST))
826     return (UnOpInit::get(getOpcode(), lhs, getType()))
827         ->Fold(R.getCurrentRecord(), R.isFinal());
828   return const_cast<UnOpInit *>(this);
829 }
830 
831 std::string UnOpInit::getAsString() const {
832   std::string Result;
833   switch (getOpcode()) {
834   case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
835   case NOT: Result = "!not"; break;
836   case HEAD: Result = "!head"; break;
837   case TAIL: Result = "!tail"; break;
838   case SIZE: Result = "!size"; break;
839   case EMPTY: Result = "!empty"; break;
840   case GETDAGOP: Result = "!getdagop"; break;
841   }
842   return Result + "(" + LHS->getAsString() + ")";
843 }
844 
845 static void
846 ProfileBinOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *RHS,
847                  RecTy *Type) {
848   ID.AddInteger(Opcode);
849   ID.AddPointer(LHS);
850   ID.AddPointer(RHS);
851   ID.AddPointer(Type);
852 }
853 
854 BinOpInit *BinOpInit::get(BinaryOp Opc, Init *LHS,
855                           Init *RHS, RecTy *Type) {
856   static FoldingSet<BinOpInit> ThePool;
857 
858   FoldingSetNodeID ID;
859   ProfileBinOpInit(ID, Opc, LHS, RHS, Type);
860 
861   void *IP = nullptr;
862   if (BinOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
863     return I;
864 
865   BinOpInit *I = new(Allocator) BinOpInit(Opc, LHS, RHS, Type);
866   ThePool.InsertNode(I, IP);
867   return I;
868 }
869 
870 void BinOpInit::Profile(FoldingSetNodeID &ID) const {
871   ProfileBinOpInit(ID, getOpcode(), getLHS(), getRHS(), getType());
872 }
873 
874 static StringInit *ConcatStringInits(const StringInit *I0,
875                                      const StringInit *I1) {
876   SmallString<80> Concat(I0->getValue());
877   Concat.append(I1->getValue());
878   return StringInit::get(Concat);
879 }
880 
881 Init *BinOpInit::getStrConcat(Init *I0, Init *I1) {
882   // Shortcut for the common case of concatenating two strings.
883   if (const StringInit *I0s = dyn_cast<StringInit>(I0))
884     if (const StringInit *I1s = dyn_cast<StringInit>(I1))
885       return ConcatStringInits(I0s, I1s);
886   return BinOpInit::get(BinOpInit::STRCONCAT, I0, I1, StringRecTy::get());
887 }
888 
889 static ListInit *ConcatListInits(const ListInit *LHS,
890                                  const ListInit *RHS) {
891   SmallVector<Init *, 8> Args;
892   Args.insert(Args.end(), LHS->begin(), LHS->end());
893   Args.insert(Args.end(), RHS->begin(), RHS->end());
894   return ListInit::get(Args, LHS->getElementType());
895 }
896 
897 Init *BinOpInit::getListConcat(TypedInit *LHS, Init *RHS) {
898   assert(isa<ListRecTy>(LHS->getType()) && "First arg must be a list");
899 
900   // Shortcut for the common case of concatenating two lists.
901    if (const ListInit *LHSList = dyn_cast<ListInit>(LHS))
902      if (const ListInit *RHSList = dyn_cast<ListInit>(RHS))
903        return ConcatListInits(LHSList, RHSList);
904    return BinOpInit::get(BinOpInit::LISTCONCAT, LHS, RHS, LHS->getType());
905 }
906 
907 Init *BinOpInit::getListSplat(TypedInit *LHS, Init *RHS) {
908   return BinOpInit::get(BinOpInit::LISTSPLAT, LHS, RHS, LHS->getType());
909 }
910 
911 Init *BinOpInit::Fold(Record *CurRec) const {
912   switch (getOpcode()) {
913   case CONCAT: {
914     DagInit *LHSs = dyn_cast<DagInit>(LHS);
915     DagInit *RHSs = dyn_cast<DagInit>(RHS);
916     if (LHSs && RHSs) {
917       DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
918       DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
919       if ((!LOp && !isa<UnsetInit>(LHSs->getOperator())) ||
920           (!ROp && !isa<UnsetInit>(RHSs->getOperator())))
921         break;
922       if (LOp && ROp && LOp->getDef() != ROp->getDef()) {
923         PrintFatalError(Twine("Concatenated Dag operators do not match: '") +
924                         LHSs->getAsString() + "' vs. '" + RHSs->getAsString() +
925                         "'");
926       }
927       Init *Op = LOp ? LOp : ROp;
928       if (!Op)
929         Op = UnsetInit::get();
930 
931       SmallVector<Init*, 8> Args;
932       SmallVector<StringInit*, 8> ArgNames;
933       for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
934         Args.push_back(LHSs->getArg(i));
935         ArgNames.push_back(LHSs->getArgName(i));
936       }
937       for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
938         Args.push_back(RHSs->getArg(i));
939         ArgNames.push_back(RHSs->getArgName(i));
940       }
941       return DagInit::get(Op, nullptr, Args, ArgNames);
942     }
943     break;
944   }
945   case LISTCONCAT: {
946     ListInit *LHSs = dyn_cast<ListInit>(LHS);
947     ListInit *RHSs = dyn_cast<ListInit>(RHS);
948     if (LHSs && RHSs) {
949       SmallVector<Init *, 8> Args;
950       Args.insert(Args.end(), LHSs->begin(), LHSs->end());
951       Args.insert(Args.end(), RHSs->begin(), RHSs->end());
952       return ListInit::get(Args, LHSs->getElementType());
953     }
954     break;
955   }
956   case LISTSPLAT: {
957     TypedInit *Value = dyn_cast<TypedInit>(LHS);
958     IntInit *Size = dyn_cast<IntInit>(RHS);
959     if (Value && Size) {
960       SmallVector<Init *, 8> Args(Size->getValue(), Value);
961       return ListInit::get(Args, Value->getType());
962     }
963     break;
964   }
965   case STRCONCAT: {
966     StringInit *LHSs = dyn_cast<StringInit>(LHS);
967     StringInit *RHSs = dyn_cast<StringInit>(RHS);
968     if (LHSs && RHSs)
969       return ConcatStringInits(LHSs, RHSs);
970     break;
971   }
972   case EQ:
973   case NE:
974   case LE:
975   case LT:
976   case GE:
977   case GT: {
978     // try to fold eq comparison for 'bit' and 'int', otherwise fallback
979     // to string objects.
980     IntInit *L =
981         dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
982     IntInit *R =
983         dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
984 
985     if (L && R) {
986       bool Result;
987       switch (getOpcode()) {
988       case EQ: Result = L->getValue() == R->getValue(); break;
989       case NE: Result = L->getValue() != R->getValue(); break;
990       case LE: Result = L->getValue() <= R->getValue(); break;
991       case LT: Result = L->getValue() < R->getValue(); break;
992       case GE: Result = L->getValue() >= R->getValue(); break;
993       case GT: Result = L->getValue() > R->getValue(); break;
994       default: llvm_unreachable("unhandled comparison");
995       }
996       return BitInit::get(Result);
997     }
998 
999     if (getOpcode() == EQ || getOpcode() == NE) {
1000       StringInit *LHSs = dyn_cast<StringInit>(LHS);
1001       StringInit *RHSs = dyn_cast<StringInit>(RHS);
1002 
1003       // Make sure we've resolved
1004       if (LHSs && RHSs) {
1005         bool Equal = LHSs->getValue() == RHSs->getValue();
1006         return BitInit::get(getOpcode() == EQ ? Equal : !Equal);
1007       }
1008     }
1009 
1010     break;
1011   }
1012   case SETDAGOP: {
1013     DagInit *Dag = dyn_cast<DagInit>(LHS);
1014     DefInit *Op = dyn_cast<DefInit>(RHS);
1015     if (Dag && Op) {
1016       SmallVector<Init*, 8> Args;
1017       SmallVector<StringInit*, 8> ArgNames;
1018       for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1019         Args.push_back(Dag->getArg(i));
1020         ArgNames.push_back(Dag->getArgName(i));
1021       }
1022       return DagInit::get(Op, nullptr, Args, ArgNames);
1023     }
1024     break;
1025   }
1026   case ADD:
1027   case MUL:
1028   case AND:
1029   case OR:
1030   case XOR:
1031   case SHL:
1032   case SRA:
1033   case SRL: {
1034     IntInit *LHSi =
1035       dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
1036     IntInit *RHSi =
1037       dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
1038     if (LHSi && RHSi) {
1039       int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
1040       int64_t Result;
1041       switch (getOpcode()) {
1042       default: llvm_unreachable("Bad opcode!");
1043       case ADD: Result = LHSv +  RHSv; break;
1044       case MUL: Result = LHSv *  RHSv; break;
1045       case AND: Result = LHSv &  RHSv; break;
1046       case OR:  Result = LHSv | RHSv; break;
1047       case XOR: Result = LHSv ^ RHSv; break;
1048       case SHL: Result = (uint64_t)LHSv << (uint64_t)RHSv; break;
1049       case SRA: Result = LHSv >> RHSv; break;
1050       case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
1051       }
1052       return IntInit::get(Result);
1053     }
1054     break;
1055   }
1056   }
1057   return const_cast<BinOpInit *>(this);
1058 }
1059 
1060 Init *BinOpInit::resolveReferences(Resolver &R) const {
1061   Init *lhs = LHS->resolveReferences(R);
1062   Init *rhs = RHS->resolveReferences(R);
1063 
1064   if (LHS != lhs || RHS != rhs)
1065     return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))
1066         ->Fold(R.getCurrentRecord());
1067   return const_cast<BinOpInit *>(this);
1068 }
1069 
1070 std::string BinOpInit::getAsString() const {
1071   std::string Result;
1072   switch (getOpcode()) {
1073   case CONCAT: Result = "!con"; break;
1074   case ADD: Result = "!add"; break;
1075   case MUL: Result = "!mul"; break;
1076   case AND: Result = "!and"; break;
1077   case OR: Result = "!or"; break;
1078   case XOR: Result = "!xor"; break;
1079   case SHL: Result = "!shl"; break;
1080   case SRA: Result = "!sra"; break;
1081   case SRL: Result = "!srl"; break;
1082   case EQ: Result = "!eq"; break;
1083   case NE: Result = "!ne"; break;
1084   case LE: Result = "!le"; break;
1085   case LT: Result = "!lt"; break;
1086   case GE: Result = "!ge"; break;
1087   case GT: Result = "!gt"; break;
1088   case LISTCONCAT: Result = "!listconcat"; break;
1089   case LISTSPLAT: Result = "!listsplat"; break;
1090   case STRCONCAT: Result = "!strconcat"; break;
1091   case SETDAGOP: Result = "!setdagop"; break;
1092   }
1093   return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
1094 }
1095 
1096 static void
1097 ProfileTernOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *MHS,
1098                   Init *RHS, RecTy *Type) {
1099   ID.AddInteger(Opcode);
1100   ID.AddPointer(LHS);
1101   ID.AddPointer(MHS);
1102   ID.AddPointer(RHS);
1103   ID.AddPointer(Type);
1104 }
1105 
1106 TernOpInit *TernOpInit::get(TernaryOp Opc, Init *LHS, Init *MHS, Init *RHS,
1107                             RecTy *Type) {
1108   static FoldingSet<TernOpInit> ThePool;
1109 
1110   FoldingSetNodeID ID;
1111   ProfileTernOpInit(ID, Opc, LHS, MHS, RHS, Type);
1112 
1113   void *IP = nullptr;
1114   if (TernOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1115     return I;
1116 
1117   TernOpInit *I = new(Allocator) TernOpInit(Opc, LHS, MHS, RHS, Type);
1118   ThePool.InsertNode(I, IP);
1119   return I;
1120 }
1121 
1122 void TernOpInit::Profile(FoldingSetNodeID &ID) const {
1123   ProfileTernOpInit(ID, getOpcode(), getLHS(), getMHS(), getRHS(), getType());
1124 }
1125 
1126 static Init *ForeachApply(Init *LHS, Init *MHSe, Init *RHS, Record *CurRec) {
1127   MapResolver R(CurRec);
1128   R.set(LHS, MHSe);
1129   return RHS->resolveReferences(R);
1130 }
1131 
1132 static Init *ForeachDagApply(Init *LHS, DagInit *MHSd, Init *RHS,
1133                              Record *CurRec) {
1134   bool Change = false;
1135   Init *Val = ForeachApply(LHS, MHSd->getOperator(), RHS, CurRec);
1136   if (Val != MHSd->getOperator())
1137     Change = true;
1138 
1139   SmallVector<std::pair<Init *, StringInit *>, 8> NewArgs;
1140   for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1141     Init *Arg = MHSd->getArg(i);
1142     Init *NewArg;
1143     StringInit *ArgName = MHSd->getArgName(i);
1144 
1145     if (DagInit *Argd = dyn_cast<DagInit>(Arg))
1146       NewArg = ForeachDagApply(LHS, Argd, RHS, CurRec);
1147     else
1148       NewArg = ForeachApply(LHS, Arg, RHS, CurRec);
1149 
1150     NewArgs.push_back(std::make_pair(NewArg, ArgName));
1151     if (Arg != NewArg)
1152       Change = true;
1153   }
1154 
1155   if (Change)
1156     return DagInit::get(Val, nullptr, NewArgs);
1157   return MHSd;
1158 }
1159 
1160 // Applies RHS to all elements of MHS, using LHS as a temp variable.
1161 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1162                            Record *CurRec) {
1163   if (DagInit *MHSd = dyn_cast<DagInit>(MHS))
1164     return ForeachDagApply(LHS, MHSd, RHS, CurRec);
1165 
1166   if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) {
1167     SmallVector<Init *, 8> NewList(MHSl->begin(), MHSl->end());
1168 
1169     for (Init *&Item : NewList) {
1170       Init *NewItem = ForeachApply(LHS, Item, RHS, CurRec);
1171       if (NewItem != Item)
1172         Item = NewItem;
1173     }
1174     return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
1175   }
1176 
1177   return nullptr;
1178 }
1179 
1180 Init *TernOpInit::Fold(Record *CurRec) const {
1181   switch (getOpcode()) {
1182   case SUBST: {
1183     DefInit *LHSd = dyn_cast<DefInit>(LHS);
1184     VarInit *LHSv = dyn_cast<VarInit>(LHS);
1185     StringInit *LHSs = dyn_cast<StringInit>(LHS);
1186 
1187     DefInit *MHSd = dyn_cast<DefInit>(MHS);
1188     VarInit *MHSv = dyn_cast<VarInit>(MHS);
1189     StringInit *MHSs = dyn_cast<StringInit>(MHS);
1190 
1191     DefInit *RHSd = dyn_cast<DefInit>(RHS);
1192     VarInit *RHSv = dyn_cast<VarInit>(RHS);
1193     StringInit *RHSs = dyn_cast<StringInit>(RHS);
1194 
1195     if (LHSd && MHSd && RHSd) {
1196       Record *Val = RHSd->getDef();
1197       if (LHSd->getAsString() == RHSd->getAsString())
1198         Val = MHSd->getDef();
1199       return DefInit::get(Val);
1200     }
1201     if (LHSv && MHSv && RHSv) {
1202       std::string Val = std::string(RHSv->getName());
1203       if (LHSv->getAsString() == RHSv->getAsString())
1204         Val = std::string(MHSv->getName());
1205       return VarInit::get(Val, getType());
1206     }
1207     if (LHSs && MHSs && RHSs) {
1208       std::string Val = std::string(RHSs->getValue());
1209 
1210       std::string::size_type found;
1211       std::string::size_type idx = 0;
1212       while (true) {
1213         found = Val.find(std::string(LHSs->getValue()), idx);
1214         if (found == std::string::npos)
1215           break;
1216         Val.replace(found, LHSs->getValue().size(),
1217                     std::string(MHSs->getValue()));
1218         idx = found + MHSs->getValue().size();
1219       }
1220 
1221       return StringInit::get(Val);
1222     }
1223     break;
1224   }
1225 
1226   case FOREACH: {
1227     if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(), CurRec))
1228       return Result;
1229     break;
1230   }
1231 
1232   case IF: {
1233     if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
1234                             LHS->convertInitializerTo(IntRecTy::get()))) {
1235       if (LHSi->getValue())
1236         return MHS;
1237       return RHS;
1238     }
1239     break;
1240   }
1241 
1242   case DAG: {
1243     ListInit *MHSl = dyn_cast<ListInit>(MHS);
1244     ListInit *RHSl = dyn_cast<ListInit>(RHS);
1245     bool MHSok = MHSl || isa<UnsetInit>(MHS);
1246     bool RHSok = RHSl || isa<UnsetInit>(RHS);
1247 
1248     if (isa<UnsetInit>(MHS) && isa<UnsetInit>(RHS))
1249       break; // Typically prevented by the parser, but might happen with template args
1250 
1251     if (MHSok && RHSok && (!MHSl || !RHSl || MHSl->size() == RHSl->size())) {
1252       SmallVector<std::pair<Init *, StringInit *>, 8> Children;
1253       unsigned Size = MHSl ? MHSl->size() : RHSl->size();
1254       for (unsigned i = 0; i != Size; ++i) {
1255         Init *Node = MHSl ? MHSl->getElement(i) : UnsetInit::get();
1256         Init *Name = RHSl ? RHSl->getElement(i) : UnsetInit::get();
1257         if (!isa<StringInit>(Name) && !isa<UnsetInit>(Name))
1258           return const_cast<TernOpInit *>(this);
1259         Children.emplace_back(Node, dyn_cast<StringInit>(Name));
1260       }
1261       return DagInit::get(LHS, nullptr, Children);
1262     }
1263     break;
1264   }
1265   }
1266 
1267   return const_cast<TernOpInit *>(this);
1268 }
1269 
1270 Init *TernOpInit::resolveReferences(Resolver &R) const {
1271   Init *lhs = LHS->resolveReferences(R);
1272 
1273   if (getOpcode() == IF && lhs != LHS) {
1274     if (IntInit *Value = dyn_cast_or_null<IntInit>(
1275                              lhs->convertInitializerTo(IntRecTy::get()))) {
1276       // Short-circuit
1277       if (Value->getValue())
1278         return MHS->resolveReferences(R);
1279       return RHS->resolveReferences(R);
1280     }
1281   }
1282 
1283   Init *mhs = MHS->resolveReferences(R);
1284   Init *rhs;
1285 
1286   if (getOpcode() == FOREACH) {
1287     ShadowResolver SR(R);
1288     SR.addShadow(lhs);
1289     rhs = RHS->resolveReferences(SR);
1290   } else {
1291     rhs = RHS->resolveReferences(R);
1292   }
1293 
1294   if (LHS != lhs || MHS != mhs || RHS != rhs)
1295     return (TernOpInit::get(getOpcode(), lhs, mhs, rhs, getType()))
1296         ->Fold(R.getCurrentRecord());
1297   return const_cast<TernOpInit *>(this);
1298 }
1299 
1300 std::string TernOpInit::getAsString() const {
1301   std::string Result;
1302   bool UnquotedLHS = false;
1303   switch (getOpcode()) {
1304   case SUBST: Result = "!subst"; break;
1305   case FOREACH: Result = "!foreach"; UnquotedLHS = true; break;
1306   case IF: Result = "!if"; break;
1307   case DAG: Result = "!dag"; break;
1308   }
1309   return (Result + "(" +
1310           (UnquotedLHS ? LHS->getAsUnquotedString() : LHS->getAsString()) +
1311           ", " + MHS->getAsString() + ", " + RHS->getAsString() + ")");
1312 }
1313 
1314 static void ProfileFoldOpInit(FoldingSetNodeID &ID, Init *A, Init *B,
1315                               Init *Start, Init *List, Init *Expr,
1316                               RecTy *Type) {
1317   ID.AddPointer(Start);
1318   ID.AddPointer(List);
1319   ID.AddPointer(A);
1320   ID.AddPointer(B);
1321   ID.AddPointer(Expr);
1322   ID.AddPointer(Type);
1323 }
1324 
1325 FoldOpInit *FoldOpInit::get(Init *Start, Init *List, Init *A, Init *B,
1326                             Init *Expr, RecTy *Type) {
1327   static FoldingSet<FoldOpInit> ThePool;
1328 
1329   FoldingSetNodeID ID;
1330   ProfileFoldOpInit(ID, Start, List, A, B, Expr, Type);
1331 
1332   void *IP = nullptr;
1333   if (FoldOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1334     return I;
1335 
1336   FoldOpInit *I = new (Allocator) FoldOpInit(Start, List, A, B, Expr, Type);
1337   ThePool.InsertNode(I, IP);
1338   return I;
1339 }
1340 
1341 void FoldOpInit::Profile(FoldingSetNodeID &ID) const {
1342   ProfileFoldOpInit(ID, Start, List, A, B, Expr, getType());
1343 }
1344 
1345 Init *FoldOpInit::Fold(Record *CurRec) const {
1346   if (ListInit *LI = dyn_cast<ListInit>(List)) {
1347     Init *Accum = Start;
1348     for (Init *Elt : *LI) {
1349       MapResolver R(CurRec);
1350       R.set(A, Accum);
1351       R.set(B, Elt);
1352       Accum = Expr->resolveReferences(R);
1353     }
1354     return Accum;
1355   }
1356   return const_cast<FoldOpInit *>(this);
1357 }
1358 
1359 Init *FoldOpInit::resolveReferences(Resolver &R) const {
1360   Init *NewStart = Start->resolveReferences(R);
1361   Init *NewList = List->resolveReferences(R);
1362   ShadowResolver SR(R);
1363   SR.addShadow(A);
1364   SR.addShadow(B);
1365   Init *NewExpr = Expr->resolveReferences(SR);
1366 
1367   if (Start == NewStart && List == NewList && Expr == NewExpr)
1368     return const_cast<FoldOpInit *>(this);
1369 
1370   return get(NewStart, NewList, A, B, NewExpr, getType())
1371       ->Fold(R.getCurrentRecord());
1372 }
1373 
1374 Init *FoldOpInit::getBit(unsigned Bit) const {
1375   return VarBitInit::get(const_cast<FoldOpInit *>(this), Bit);
1376 }
1377 
1378 std::string FoldOpInit::getAsString() const {
1379   return (Twine("!foldl(") + Start->getAsString() + ", " + List->getAsString() +
1380           ", " + A->getAsUnquotedString() + ", " + B->getAsUnquotedString() +
1381           ", " + Expr->getAsString() + ")")
1382       .str();
1383 }
1384 
1385 static void ProfileIsAOpInit(FoldingSetNodeID &ID, RecTy *CheckType,
1386                              Init *Expr) {
1387   ID.AddPointer(CheckType);
1388   ID.AddPointer(Expr);
1389 }
1390 
1391 IsAOpInit *IsAOpInit::get(RecTy *CheckType, Init *Expr) {
1392   static FoldingSet<IsAOpInit> ThePool;
1393 
1394   FoldingSetNodeID ID;
1395   ProfileIsAOpInit(ID, CheckType, Expr);
1396 
1397   void *IP = nullptr;
1398   if (IsAOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1399     return I;
1400 
1401   IsAOpInit *I = new (Allocator) IsAOpInit(CheckType, Expr);
1402   ThePool.InsertNode(I, IP);
1403   return I;
1404 }
1405 
1406 void IsAOpInit::Profile(FoldingSetNodeID &ID) const {
1407   ProfileIsAOpInit(ID, CheckType, Expr);
1408 }
1409 
1410 Init *IsAOpInit::Fold() const {
1411   if (TypedInit *TI = dyn_cast<TypedInit>(Expr)) {
1412     // Is the expression type known to be (a subclass of) the desired type?
1413     if (TI->getType()->typeIsConvertibleTo(CheckType))
1414       return IntInit::get(1);
1415 
1416     if (isa<RecordRecTy>(CheckType)) {
1417       // If the target type is not a subclass of the expression type, or if
1418       // the expression has fully resolved to a record, we know that it can't
1419       // be of the required type.
1420       if (!CheckType->typeIsConvertibleTo(TI->getType()) || isa<DefInit>(Expr))
1421         return IntInit::get(0);
1422     } else {
1423       // We treat non-record types as not castable.
1424       return IntInit::get(0);
1425     }
1426   }
1427   return const_cast<IsAOpInit *>(this);
1428 }
1429 
1430 Init *IsAOpInit::resolveReferences(Resolver &R) const {
1431   Init *NewExpr = Expr->resolveReferences(R);
1432   if (Expr != NewExpr)
1433     return get(CheckType, NewExpr)->Fold();
1434   return const_cast<IsAOpInit *>(this);
1435 }
1436 
1437 Init *IsAOpInit::getBit(unsigned Bit) const {
1438   return VarBitInit::get(const_cast<IsAOpInit *>(this), Bit);
1439 }
1440 
1441 std::string IsAOpInit::getAsString() const {
1442   return (Twine("!isa<") + CheckType->getAsString() + ">(" +
1443           Expr->getAsString() + ")")
1444       .str();
1445 }
1446 
1447 RecTy *TypedInit::getFieldType(StringInit *FieldName) const {
1448   if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType())) {
1449     for (Record *Rec : RecordType->getClasses()) {
1450       if (RecordVal *Field = Rec->getValue(FieldName))
1451         return Field->getType();
1452     }
1453   }
1454   return nullptr;
1455 }
1456 
1457 Init *
1458 TypedInit::convertInitializerTo(RecTy *Ty) const {
1459   if (getType() == Ty || getType()->typeIsA(Ty))
1460     return const_cast<TypedInit *>(this);
1461 
1462   if (isa<BitRecTy>(getType()) && isa<BitsRecTy>(Ty) &&
1463       cast<BitsRecTy>(Ty)->getNumBits() == 1)
1464     return BitsInit::get({const_cast<TypedInit *>(this)});
1465 
1466   return nullptr;
1467 }
1468 
1469 Init *TypedInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
1470   BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1471   if (!T) return nullptr;  // Cannot subscript a non-bits variable.
1472   unsigned NumBits = T->getNumBits();
1473 
1474   SmallVector<Init *, 16> NewBits;
1475   NewBits.reserve(Bits.size());
1476   for (unsigned Bit : Bits) {
1477     if (Bit >= NumBits)
1478       return nullptr;
1479 
1480     NewBits.push_back(VarBitInit::get(const_cast<TypedInit *>(this), Bit));
1481   }
1482   return BitsInit::get(NewBits);
1483 }
1484 
1485 Init *TypedInit::getCastTo(RecTy *Ty) const {
1486   // Handle the common case quickly
1487   if (getType() == Ty || getType()->typeIsA(Ty))
1488     return const_cast<TypedInit *>(this);
1489 
1490   if (Init *Converted = convertInitializerTo(Ty)) {
1491     assert(!isa<TypedInit>(Converted) ||
1492            cast<TypedInit>(Converted)->getType()->typeIsA(Ty));
1493     return Converted;
1494   }
1495 
1496   if (!getType()->typeIsConvertibleTo(Ty))
1497     return nullptr;
1498 
1499   return UnOpInit::get(UnOpInit::CAST, const_cast<TypedInit *>(this), Ty)
1500       ->Fold(nullptr);
1501 }
1502 
1503 Init *TypedInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
1504   ListRecTy *T = dyn_cast<ListRecTy>(getType());
1505   if (!T) return nullptr;  // Cannot subscript a non-list variable.
1506 
1507   if (Elements.size() == 1)
1508     return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1509 
1510   SmallVector<Init*, 8> ListInits;
1511   ListInits.reserve(Elements.size());
1512   for (unsigned Element : Elements)
1513     ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1514                                                 Element));
1515   return ListInit::get(ListInits, T->getElementType());
1516 }
1517 
1518 
1519 VarInit *VarInit::get(StringRef VN, RecTy *T) {
1520   Init *Value = StringInit::get(VN);
1521   return VarInit::get(Value, T);
1522 }
1523 
1524 VarInit *VarInit::get(Init *VN, RecTy *T) {
1525   using Key = std::pair<RecTy *, Init *>;
1526   static DenseMap<Key, VarInit*> ThePool;
1527 
1528   Key TheKey(std::make_pair(T, VN));
1529 
1530   VarInit *&I = ThePool[TheKey];
1531   if (!I)
1532     I = new(Allocator) VarInit(VN, T);
1533   return I;
1534 }
1535 
1536 StringRef VarInit::getName() const {
1537   StringInit *NameString = cast<StringInit>(getNameInit());
1538   return NameString->getValue();
1539 }
1540 
1541 Init *VarInit::getBit(unsigned Bit) const {
1542   if (getType() == BitRecTy::get())
1543     return const_cast<VarInit*>(this);
1544   return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1545 }
1546 
1547 Init *VarInit::resolveReferences(Resolver &R) const {
1548   if (Init *Val = R.resolve(VarName))
1549     return Val;
1550   return const_cast<VarInit *>(this);
1551 }
1552 
1553 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1554   using Key = std::pair<TypedInit *, unsigned>;
1555   static DenseMap<Key, VarBitInit*> ThePool;
1556 
1557   Key TheKey(std::make_pair(T, B));
1558 
1559   VarBitInit *&I = ThePool[TheKey];
1560   if (!I)
1561     I = new(Allocator) VarBitInit(T, B);
1562   return I;
1563 }
1564 
1565 std::string VarBitInit::getAsString() const {
1566   return TI->getAsString() + "{" + utostr(Bit) + "}";
1567 }
1568 
1569 Init *VarBitInit::resolveReferences(Resolver &R) const {
1570   Init *I = TI->resolveReferences(R);
1571   if (TI != I)
1572     return I->getBit(getBitNum());
1573 
1574   return const_cast<VarBitInit*>(this);
1575 }
1576 
1577 VarListElementInit *VarListElementInit::get(TypedInit *T,
1578                                             unsigned E) {
1579   using Key = std::pair<TypedInit *, unsigned>;
1580   static DenseMap<Key, VarListElementInit*> ThePool;
1581 
1582   Key TheKey(std::make_pair(T, E));
1583 
1584   VarListElementInit *&I = ThePool[TheKey];
1585   if (!I) I = new(Allocator) VarListElementInit(T, E);
1586   return I;
1587 }
1588 
1589 std::string VarListElementInit::getAsString() const {
1590   return TI->getAsString() + "[" + utostr(Element) + "]";
1591 }
1592 
1593 Init *VarListElementInit::resolveReferences(Resolver &R) const {
1594   Init *NewTI = TI->resolveReferences(R);
1595   if (ListInit *List = dyn_cast<ListInit>(NewTI)) {
1596     // Leave out-of-bounds array references as-is. This can happen without
1597     // being an error, e.g. in the untaken "branch" of an !if expression.
1598     if (getElementNum() < List->size())
1599       return List->getElement(getElementNum());
1600   }
1601   if (NewTI != TI && isa<TypedInit>(NewTI))
1602     return VarListElementInit::get(cast<TypedInit>(NewTI), getElementNum());
1603   return const_cast<VarListElementInit *>(this);
1604 }
1605 
1606 Init *VarListElementInit::getBit(unsigned Bit) const {
1607   if (getType() == BitRecTy::get())
1608     return const_cast<VarListElementInit*>(this);
1609   return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1610 }
1611 
1612 DefInit::DefInit(Record *D)
1613     : TypedInit(IK_DefInit, D->getType()), Def(D) {}
1614 
1615 DefInit *DefInit::get(Record *R) {
1616   return R->getDefInit();
1617 }
1618 
1619 Init *DefInit::convertInitializerTo(RecTy *Ty) const {
1620   if (auto *RRT = dyn_cast<RecordRecTy>(Ty))
1621     if (getType()->typeIsConvertibleTo(RRT))
1622       return const_cast<DefInit *>(this);
1623   return nullptr;
1624 }
1625 
1626 RecTy *DefInit::getFieldType(StringInit *FieldName) const {
1627   if (const RecordVal *RV = Def->getValue(FieldName))
1628     return RV->getType();
1629   return nullptr;
1630 }
1631 
1632 std::string DefInit::getAsString() const { return std::string(Def->getName()); }
1633 
1634 static void ProfileVarDefInit(FoldingSetNodeID &ID,
1635                               Record *Class,
1636                               ArrayRef<Init *> Args) {
1637   ID.AddInteger(Args.size());
1638   ID.AddPointer(Class);
1639 
1640   for (Init *I : Args)
1641     ID.AddPointer(I);
1642 }
1643 
1644 VarDefInit *VarDefInit::get(Record *Class, ArrayRef<Init *> Args) {
1645   static FoldingSet<VarDefInit> ThePool;
1646 
1647   FoldingSetNodeID ID;
1648   ProfileVarDefInit(ID, Class, Args);
1649 
1650   void *IP = nullptr;
1651   if (VarDefInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1652     return I;
1653 
1654   void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Args.size()),
1655                                  alignof(VarDefInit));
1656   VarDefInit *I = new(Mem) VarDefInit(Class, Args.size());
1657   std::uninitialized_copy(Args.begin(), Args.end(),
1658                           I->getTrailingObjects<Init *>());
1659   ThePool.InsertNode(I, IP);
1660   return I;
1661 }
1662 
1663 void VarDefInit::Profile(FoldingSetNodeID &ID) const {
1664   ProfileVarDefInit(ID, Class, args());
1665 }
1666 
1667 DefInit *VarDefInit::instantiate() {
1668   if (!Def) {
1669     RecordKeeper &Records = Class->getRecords();
1670     auto NewRecOwner = std::make_unique<Record>(Records.getNewAnonymousName(),
1671                                            Class->getLoc(), Records,
1672                                            /*IsAnonymous=*/true);
1673     Record *NewRec = NewRecOwner.get();
1674 
1675     // Copy values from class to instance
1676     for (const RecordVal &Val : Class->getValues())
1677       NewRec->addValue(Val);
1678 
1679     // Substitute and resolve template arguments
1680     ArrayRef<Init *> TArgs = Class->getTemplateArgs();
1681     MapResolver R(NewRec);
1682 
1683     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1684       if (i < args_size())
1685         R.set(TArgs[i], getArg(i));
1686       else
1687         R.set(TArgs[i], NewRec->getValue(TArgs[i])->getValue());
1688 
1689       NewRec->removeValue(TArgs[i]);
1690     }
1691 
1692     NewRec->resolveReferences(R);
1693 
1694     // Add superclasses.
1695     ArrayRef<std::pair<Record *, SMRange>> SCs = Class->getSuperClasses();
1696     for (const auto &SCPair : SCs)
1697       NewRec->addSuperClass(SCPair.first, SCPair.second);
1698 
1699     NewRec->addSuperClass(Class,
1700                           SMRange(Class->getLoc().back(),
1701                                   Class->getLoc().back()));
1702 
1703     // Resolve internal references and store in record keeper
1704     NewRec->resolveReferences();
1705     Records.addDef(std::move(NewRecOwner));
1706 
1707     Def = DefInit::get(NewRec);
1708   }
1709 
1710   return Def;
1711 }
1712 
1713 Init *VarDefInit::resolveReferences(Resolver &R) const {
1714   TrackUnresolvedResolver UR(&R);
1715   bool Changed = false;
1716   SmallVector<Init *, 8> NewArgs;
1717   NewArgs.reserve(args_size());
1718 
1719   for (Init *Arg : args()) {
1720     Init *NewArg = Arg->resolveReferences(UR);
1721     NewArgs.push_back(NewArg);
1722     Changed |= NewArg != Arg;
1723   }
1724 
1725   if (Changed) {
1726     auto New = VarDefInit::get(Class, NewArgs);
1727     if (!UR.foundUnresolved())
1728       return New->instantiate();
1729     return New;
1730   }
1731   return const_cast<VarDefInit *>(this);
1732 }
1733 
1734 Init *VarDefInit::Fold() const {
1735   if (Def)
1736     return Def;
1737 
1738   TrackUnresolvedResolver R;
1739   for (Init *Arg : args())
1740     Arg->resolveReferences(R);
1741 
1742   if (!R.foundUnresolved())
1743     return const_cast<VarDefInit *>(this)->instantiate();
1744   return const_cast<VarDefInit *>(this);
1745 }
1746 
1747 std::string VarDefInit::getAsString() const {
1748   std::string Result = Class->getNameInitAsString() + "<";
1749   const char *sep = "";
1750   for (Init *Arg : args()) {
1751     Result += sep;
1752     sep = ", ";
1753     Result += Arg->getAsString();
1754   }
1755   return Result + ">";
1756 }
1757 
1758 FieldInit *FieldInit::get(Init *R, StringInit *FN) {
1759   using Key = std::pair<Init *, StringInit *>;
1760   static DenseMap<Key, FieldInit*> ThePool;
1761 
1762   Key TheKey(std::make_pair(R, FN));
1763 
1764   FieldInit *&I = ThePool[TheKey];
1765   if (!I) I = new(Allocator) FieldInit(R, FN);
1766   return I;
1767 }
1768 
1769 Init *FieldInit::getBit(unsigned Bit) const {
1770   if (getType() == BitRecTy::get())
1771     return const_cast<FieldInit*>(this);
1772   return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1773 }
1774 
1775 Init *FieldInit::resolveReferences(Resolver &R) const {
1776   Init *NewRec = Rec->resolveReferences(R);
1777   if (NewRec != Rec)
1778     return FieldInit::get(NewRec, FieldName)->Fold(R.getCurrentRecord());
1779   return const_cast<FieldInit *>(this);
1780 }
1781 
1782 Init *FieldInit::Fold(Record *CurRec) const {
1783   if (DefInit *DI = dyn_cast<DefInit>(Rec)) {
1784     Record *Def = DI->getDef();
1785     if (Def == CurRec)
1786       PrintFatalError(CurRec->getLoc(),
1787                       Twine("Attempting to access field '") +
1788                       FieldName->getAsUnquotedString() + "' of '" +
1789                       Rec->getAsString() + "' is a forbidden self-reference");
1790     Init *FieldVal = Def->getValue(FieldName)->getValue();
1791     if (FieldVal->isComplete())
1792       return FieldVal;
1793   }
1794   return const_cast<FieldInit *>(this);
1795 }
1796 
1797 bool FieldInit::isConcrete() const {
1798   if (DefInit *DI = dyn_cast<DefInit>(Rec)) {
1799     Init *FieldVal = DI->getDef()->getValue(FieldName)->getValue();
1800     return FieldVal->isConcrete();
1801   }
1802   return false;
1803 }
1804 
1805 static void ProfileCondOpInit(FoldingSetNodeID &ID,
1806                              ArrayRef<Init *> CondRange,
1807                              ArrayRef<Init *> ValRange,
1808                              const RecTy *ValType) {
1809   assert(CondRange.size() == ValRange.size() &&
1810          "Number of conditions and values must match!");
1811   ID.AddPointer(ValType);
1812   ArrayRef<Init *>::iterator Case = CondRange.begin();
1813   ArrayRef<Init *>::iterator Val = ValRange.begin();
1814 
1815   while (Case != CondRange.end()) {
1816     ID.AddPointer(*Case++);
1817     ID.AddPointer(*Val++);
1818   }
1819 }
1820 
1821 void CondOpInit::Profile(FoldingSetNodeID &ID) const {
1822   ProfileCondOpInit(ID,
1823       makeArrayRef(getTrailingObjects<Init *>(), NumConds),
1824       makeArrayRef(getTrailingObjects<Init *>() + NumConds, NumConds),
1825       ValType);
1826 }
1827 
1828 CondOpInit *
1829 CondOpInit::get(ArrayRef<Init *> CondRange,
1830                 ArrayRef<Init *> ValRange, RecTy *Ty) {
1831   assert(CondRange.size() == ValRange.size() &&
1832          "Number of conditions and values must match!");
1833 
1834   static FoldingSet<CondOpInit> ThePool;
1835   FoldingSetNodeID ID;
1836   ProfileCondOpInit(ID, CondRange, ValRange, Ty);
1837 
1838   void *IP = nullptr;
1839   if (CondOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1840     return I;
1841 
1842   void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(2*CondRange.size()),
1843                                  alignof(BitsInit));
1844   CondOpInit *I = new(Mem) CondOpInit(CondRange.size(), Ty);
1845 
1846   std::uninitialized_copy(CondRange.begin(), CondRange.end(),
1847                           I->getTrailingObjects<Init *>());
1848   std::uninitialized_copy(ValRange.begin(), ValRange.end(),
1849                           I->getTrailingObjects<Init *>()+CondRange.size());
1850   ThePool.InsertNode(I, IP);
1851   return I;
1852 }
1853 
1854 Init *CondOpInit::resolveReferences(Resolver &R) const {
1855   SmallVector<Init*, 4> NewConds;
1856   bool Changed = false;
1857   for (const Init *Case : getConds()) {
1858     Init *NewCase = Case->resolveReferences(R);
1859     NewConds.push_back(NewCase);
1860     Changed |= NewCase != Case;
1861   }
1862 
1863   SmallVector<Init*, 4> NewVals;
1864   for (const Init *Val : getVals()) {
1865     Init *NewVal = Val->resolveReferences(R);
1866     NewVals.push_back(NewVal);
1867     Changed |= NewVal != Val;
1868   }
1869 
1870   if (Changed)
1871     return (CondOpInit::get(NewConds, NewVals,
1872             getValType()))->Fold(R.getCurrentRecord());
1873 
1874   return const_cast<CondOpInit *>(this);
1875 }
1876 
1877 Init *CondOpInit::Fold(Record *CurRec) const {
1878   for ( unsigned i = 0; i < NumConds; ++i) {
1879     Init *Cond = getCond(i);
1880     Init *Val = getVal(i);
1881 
1882     if (IntInit *CondI = dyn_cast_or_null<IntInit>(
1883             Cond->convertInitializerTo(IntRecTy::get()))) {
1884       if (CondI->getValue())
1885         return Val->convertInitializerTo(getValType());
1886     } else
1887      return const_cast<CondOpInit *>(this);
1888   }
1889 
1890   PrintFatalError(CurRec->getLoc(),
1891                   CurRec->getName() +
1892                   " does not have any true condition in:" +
1893                   this->getAsString());
1894   return nullptr;
1895 }
1896 
1897 bool CondOpInit::isConcrete() const {
1898   for (const Init *Case : getConds())
1899     if (!Case->isConcrete())
1900       return false;
1901 
1902   for (const Init *Val : getVals())
1903     if (!Val->isConcrete())
1904       return false;
1905 
1906   return true;
1907 }
1908 
1909 bool CondOpInit::isComplete() const {
1910   for (const Init *Case : getConds())
1911     if (!Case->isComplete())
1912       return false;
1913 
1914   for (const Init *Val : getVals())
1915     if (!Val->isConcrete())
1916       return false;
1917 
1918   return true;
1919 }
1920 
1921 std::string CondOpInit::getAsString() const {
1922   std::string Result = "!cond(";
1923   for (unsigned i = 0; i < getNumConds(); i++) {
1924     Result += getCond(i)->getAsString() + ": ";
1925     Result += getVal(i)->getAsString();
1926     if (i != getNumConds()-1)
1927       Result += ", ";
1928   }
1929   return Result + ")";
1930 }
1931 
1932 Init *CondOpInit::getBit(unsigned Bit) const {
1933   return VarBitInit::get(const_cast<CondOpInit *>(this), Bit);
1934 }
1935 
1936 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, StringInit *VN,
1937                            ArrayRef<Init *> ArgRange,
1938                            ArrayRef<StringInit *> NameRange) {
1939   ID.AddPointer(V);
1940   ID.AddPointer(VN);
1941 
1942   ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1943   ArrayRef<StringInit *>::iterator Name = NameRange.begin();
1944   while (Arg != ArgRange.end()) {
1945     assert(Name != NameRange.end() && "Arg name underflow!");
1946     ID.AddPointer(*Arg++);
1947     ID.AddPointer(*Name++);
1948   }
1949   assert(Name == NameRange.end() && "Arg name overflow!");
1950 }
1951 
1952 DagInit *
1953 DagInit::get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
1954              ArrayRef<StringInit *> NameRange) {
1955   static FoldingSet<DagInit> ThePool;
1956 
1957   FoldingSetNodeID ID;
1958   ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1959 
1960   void *IP = nullptr;
1961   if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1962     return I;
1963 
1964   void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *, StringInit *>(ArgRange.size(), NameRange.size()), alignof(BitsInit));
1965   DagInit *I = new(Mem) DagInit(V, VN, ArgRange.size(), NameRange.size());
1966   std::uninitialized_copy(ArgRange.begin(), ArgRange.end(),
1967                           I->getTrailingObjects<Init *>());
1968   std::uninitialized_copy(NameRange.begin(), NameRange.end(),
1969                           I->getTrailingObjects<StringInit *>());
1970   ThePool.InsertNode(I, IP);
1971   return I;
1972 }
1973 
1974 DagInit *
1975 DagInit::get(Init *V, StringInit *VN,
1976              ArrayRef<std::pair<Init*, StringInit*>> args) {
1977   SmallVector<Init *, 8> Args;
1978   SmallVector<StringInit *, 8> Names;
1979 
1980   for (const auto &Arg : args) {
1981     Args.push_back(Arg.first);
1982     Names.push_back(Arg.second);
1983   }
1984 
1985   return DagInit::get(V, VN, Args, Names);
1986 }
1987 
1988 void DagInit::Profile(FoldingSetNodeID &ID) const {
1989   ProfileDagInit(ID, Val, ValName, makeArrayRef(getTrailingObjects<Init *>(), NumArgs), makeArrayRef(getTrailingObjects<StringInit *>(), NumArgNames));
1990 }
1991 
1992 Record *DagInit::getOperatorAsDef(ArrayRef<SMLoc> Loc) const {
1993   if (DefInit *DefI = dyn_cast<DefInit>(Val))
1994     return DefI->getDef();
1995   PrintFatalError(Loc, "Expected record as operator");
1996   return nullptr;
1997 }
1998 
1999 Init *DagInit::resolveReferences(Resolver &R) const {
2000   SmallVector<Init*, 8> NewArgs;
2001   NewArgs.reserve(arg_size());
2002   bool ArgsChanged = false;
2003   for (const Init *Arg : getArgs()) {
2004     Init *NewArg = Arg->resolveReferences(R);
2005     NewArgs.push_back(NewArg);
2006     ArgsChanged |= NewArg != Arg;
2007   }
2008 
2009   Init *Op = Val->resolveReferences(R);
2010   if (Op != Val || ArgsChanged)
2011     return DagInit::get(Op, ValName, NewArgs, getArgNames());
2012 
2013   return const_cast<DagInit *>(this);
2014 }
2015 
2016 bool DagInit::isConcrete() const {
2017   if (!Val->isConcrete())
2018     return false;
2019   for (const Init *Elt : getArgs()) {
2020     if (!Elt->isConcrete())
2021       return false;
2022   }
2023   return true;
2024 }
2025 
2026 std::string DagInit::getAsString() const {
2027   std::string Result = "(" + Val->getAsString();
2028   if (ValName)
2029     Result += ":" + ValName->getAsUnquotedString();
2030   if (!arg_empty()) {
2031     Result += " " + getArg(0)->getAsString();
2032     if (getArgName(0)) Result += ":$" + getArgName(0)->getAsUnquotedString();
2033     for (unsigned i = 1, e = getNumArgs(); i != e; ++i) {
2034       Result += ", " + getArg(i)->getAsString();
2035       if (getArgName(i)) Result += ":$" + getArgName(i)->getAsUnquotedString();
2036     }
2037   }
2038   return Result + ")";
2039 }
2040 
2041 //===----------------------------------------------------------------------===//
2042 //    Other implementations
2043 //===----------------------------------------------------------------------===//
2044 
2045 RecordVal::RecordVal(Init *N, RecTy *T, bool P)
2046   : Name(N), TyAndPrefix(T, P) {
2047   setValue(UnsetInit::get());
2048   assert(Value && "Cannot create unset value for current type!");
2049 }
2050 
2051 // This constructor accepts the same arguments as the above, but also
2052 // a source location.
2053 RecordVal::RecordVal(Init *N, SMLoc Loc, RecTy *T, bool P)
2054     : Name(N), Loc(Loc), TyAndPrefix(T, P) {
2055   setValue(UnsetInit::get());
2056   assert(Value && "Cannot create unset value for current type!");
2057 }
2058 
2059 StringRef RecordVal::getName() const {
2060   return cast<StringInit>(getNameInit())->getValue();
2061 }
2062 
2063 bool RecordVal::setValue(Init *V) {
2064   if (V) {
2065     Value = V->getCastTo(getType());
2066     if (Value) {
2067       assert(!isa<TypedInit>(Value) ||
2068              cast<TypedInit>(Value)->getType()->typeIsA(getType()));
2069       if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {
2070         if (!isa<BitsInit>(Value)) {
2071           SmallVector<Init *, 64> Bits;
2072           Bits.reserve(BTy->getNumBits());
2073           for (unsigned I = 0, E = BTy->getNumBits(); I < E; ++I)
2074             Bits.push_back(Value->getBit(I));
2075           Value = BitsInit::get(Bits);
2076         }
2077       }
2078     }
2079     return Value == nullptr;
2080   }
2081   Value = nullptr;
2082   return false;
2083 }
2084 
2085 // This version of setValue takes an source location and resets the
2086 // location in the RecordVal.
2087 bool RecordVal::setValue(Init *V, SMLoc NewLoc) {
2088   Loc = NewLoc;
2089   if (V) {
2090     Value = V->getCastTo(getType());
2091     if (Value) {
2092       assert(!isa<TypedInit>(Value) ||
2093              cast<TypedInit>(Value)->getType()->typeIsA(getType()));
2094       if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {
2095         if (!isa<BitsInit>(Value)) {
2096           SmallVector<Init *, 64> Bits;
2097           Bits.reserve(BTy->getNumBits());
2098           for (unsigned I = 0, E = BTy->getNumBits(); I < E; ++I)
2099             Bits.push_back(Value->getBit(I));
2100           Value = BitsInit::get(Bits);
2101         }
2102       }
2103     }
2104     return Value == nullptr;
2105   }
2106   Value = nullptr;
2107   return false;
2108 }
2109 
2110 #include "llvm/TableGen/Record.h"
2111 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2112 LLVM_DUMP_METHOD void RecordVal::dump() const { errs() << *this; }
2113 #endif
2114 
2115 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
2116   if (getPrefix()) OS << "field ";
2117   OS << *getType() << " " << getNameInitAsString();
2118 
2119   if (getValue())
2120     OS << " = " << *getValue();
2121 
2122   if (PrintSem) OS << ";\n";
2123 }
2124 
2125 unsigned Record::LastID = 0;
2126 
2127 void Record::checkName() {
2128   // Ensure the record name has string type.
2129   const TypedInit *TypedName = cast<const TypedInit>(Name);
2130   if (!isa<StringRecTy>(TypedName->getType()))
2131     PrintFatalError(getLoc(), Twine("Record name '") + Name->getAsString() +
2132                                   "' is not a string!");
2133 }
2134 
2135 RecordRecTy *Record::getType() {
2136   SmallVector<Record *, 4> DirectSCs;
2137   getDirectSuperClasses(DirectSCs);
2138   return RecordRecTy::get(DirectSCs);
2139 }
2140 
2141 DefInit *Record::getDefInit() {
2142   if (!CorrespondingDefInit)
2143     CorrespondingDefInit = new (Allocator) DefInit(this);
2144   return CorrespondingDefInit;
2145 }
2146 
2147 void Record::setName(Init *NewName) {
2148   Name = NewName;
2149   checkName();
2150   // DO NOT resolve record values to the name at this point because
2151   // there might be default values for arguments of this def.  Those
2152   // arguments might not have been resolved yet so we don't want to
2153   // prematurely assume values for those arguments were not passed to
2154   // this def.
2155   //
2156   // Nonetheless, it may be that some of this Record's values
2157   // reference the record name.  Indeed, the reason for having the
2158   // record name be an Init is to provide this flexibility.  The extra
2159   // resolve steps after completely instantiating defs takes care of
2160   // this.  See TGParser::ParseDef and TGParser::ParseDefm.
2161 }
2162 
2163 // NOTE for the next two functions:
2164 // Superclasses are in post-order, so the final one is a direct
2165 // superclass. All of its transitive superclases immediately precede it,
2166 // so we can step through the direct superclasses in reverse order.
2167 
2168 bool Record::hasDirectSuperClass(const Record *Superclass) const {
2169   ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();
2170 
2171   for (int I = SCs.size() - 1; I >= 0; --I) {
2172     const Record *SC = SCs[I].first;
2173     if (SC == Superclass)
2174       return true;
2175     I -= SC->getSuperClasses().size();
2176   }
2177 
2178   return false;
2179 }
2180 
2181 void Record::getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const {
2182   ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();
2183 
2184   while (!SCs.empty()) {
2185     Record *SC = SCs.back().first;
2186     SCs = SCs.drop_back(1 + SC->getSuperClasses().size());
2187     Classes.push_back(SC);
2188   }
2189 }
2190 
2191 void Record::resolveReferences(Resolver &R, const RecordVal *SkipVal) {
2192   for (RecordVal &Value : Values) {
2193     if (SkipVal == &Value) // Skip resolve the same field as the given one
2194       continue;
2195     if (Init *V = Value.getValue()) {
2196       Init *VR = V->resolveReferences(R);
2197       if (Value.setValue(VR)) {
2198         std::string Type;
2199         if (TypedInit *VRT = dyn_cast<TypedInit>(VR))
2200           Type =
2201               (Twine("of type '") + VRT->getType()->getAsString() + "' ").str();
2202         PrintFatalError(getLoc(), Twine("Invalid value ") + Type +
2203                                       "is found when setting '" +
2204                                       Value.getNameInitAsString() +
2205                                       "' of type '" +
2206                                       Value.getType()->getAsString() +
2207                                       "' after resolving references: " +
2208                                       VR->getAsUnquotedString() + "\n");
2209       }
2210     }
2211   }
2212   Init *OldName = getNameInit();
2213   Init *NewName = Name->resolveReferences(R);
2214   if (NewName != OldName) {
2215     // Re-register with RecordKeeper.
2216     setName(NewName);
2217   }
2218 }
2219 
2220 void Record::resolveReferences() {
2221   RecordResolver R(*this);
2222   R.setFinal(true);
2223   resolveReferences(R);
2224 }
2225 
2226 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2227 LLVM_DUMP_METHOD void Record::dump() const { errs() << *this; }
2228 #endif
2229 
2230 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
2231   OS << R.getNameInitAsString();
2232 
2233   ArrayRef<Init *> TArgs = R.getTemplateArgs();
2234   if (!TArgs.empty()) {
2235     OS << "<";
2236     bool NeedComma = false;
2237     for (const Init *TA : TArgs) {
2238       if (NeedComma) OS << ", ";
2239       NeedComma = true;
2240       const RecordVal *RV = R.getValue(TA);
2241       assert(RV && "Template argument record not found??");
2242       RV->print(OS, false);
2243     }
2244     OS << ">";
2245   }
2246 
2247   OS << " {";
2248   ArrayRef<std::pair<Record *, SMRange>> SC = R.getSuperClasses();
2249   if (!SC.empty()) {
2250     OS << "\t//";
2251     for (const auto &SuperPair : SC)
2252       OS << " " << SuperPair.first->getNameInitAsString();
2253   }
2254   OS << "\n";
2255 
2256   for (const RecordVal &Val : R.getValues())
2257     if (Val.getPrefix() && !R.isTemplateArg(Val.getNameInit()))
2258       OS << Val;
2259   for (const RecordVal &Val : R.getValues())
2260     if (!Val.getPrefix() && !R.isTemplateArg(Val.getNameInit()))
2261       OS << Val;
2262 
2263   return OS << "}\n";
2264 }
2265 
2266 Init *Record::getValueInit(StringRef FieldName) const {
2267   const RecordVal *R = getValue(FieldName);
2268   if (!R || !R->getValue())
2269     PrintFatalError(getLoc(), "Record `" + getName() +
2270       "' does not have a field named `" + FieldName + "'!\n");
2271   return R->getValue();
2272 }
2273 
2274 StringRef Record::getValueAsString(StringRef FieldName) const {
2275   llvm::Optional<StringRef> S = getValueAsOptionalString(FieldName);
2276   if (!S.hasValue())
2277     PrintFatalError(getLoc(), "Record `" + getName() +
2278       "' does not have a field named `" + FieldName + "'!\n");
2279   return S.getValue();
2280 }
2281 llvm::Optional<StringRef>
2282 Record::getValueAsOptionalString(StringRef FieldName) const {
2283   const RecordVal *R = getValue(FieldName);
2284   if (!R || !R->getValue())
2285     return llvm::Optional<StringRef>();
2286   if (isa<UnsetInit>(R->getValue()))
2287     return llvm::Optional<StringRef>();
2288 
2289   if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
2290     return SI->getValue();
2291   if (CodeInit *CI = dyn_cast<CodeInit>(R->getValue()))
2292     return CI->getValue();
2293 
2294   PrintFatalError(getLoc(),
2295                   "Record `" + getName() + "', ` field `" + FieldName +
2296                       "' exists but does not have a string initializer!");
2297 }
2298 llvm::Optional<StringRef>
2299 Record::getValueAsOptionalCode(StringRef FieldName) const {
2300   const RecordVal *R = getValue(FieldName);
2301   if (!R || !R->getValue())
2302     return llvm::Optional<StringRef>();
2303   if (isa<UnsetInit>(R->getValue()))
2304     return llvm::Optional<StringRef>();
2305 
2306   if (CodeInit *CI = dyn_cast<CodeInit>(R->getValue()))
2307     return CI->getValue();
2308 
2309   PrintFatalError(getLoc(),
2310                   "Record `" + getName() + "', field `" + FieldName +
2311                       "' exists but does not have a code initializer!");
2312 }
2313 
2314 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
2315   const RecordVal *R = getValue(FieldName);
2316   if (!R || !R->getValue())
2317     PrintFatalError(getLoc(), "Record `" + getName() +
2318       "' does not have a field named `" + FieldName + "'!\n");
2319 
2320   if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
2321     return BI;
2322   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +
2323                                 "' exists but does not have a bits value");
2324 }
2325 
2326 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
2327   const RecordVal *R = getValue(FieldName);
2328   if (!R || !R->getValue())
2329     PrintFatalError(getLoc(), "Record `" + getName() +
2330       "' does not have a field named `" + FieldName + "'!\n");
2331 
2332   if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
2333     return LI;
2334   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +
2335                                 "' exists but does not have a list value");
2336 }
2337 
2338 std::vector<Record*>
2339 Record::getValueAsListOfDefs(StringRef FieldName) const {
2340   ListInit *List = getValueAsListInit(FieldName);
2341   std::vector<Record*> Defs;
2342   for (Init *I : List->getValues()) {
2343     if (DefInit *DI = dyn_cast<DefInit>(I))
2344       Defs.push_back(DI->getDef());
2345     else
2346       PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2347         FieldName + "' list is not entirely DefInit!");
2348   }
2349   return Defs;
2350 }
2351 
2352 int64_t Record::getValueAsInt(StringRef FieldName) const {
2353   const RecordVal *R = getValue(FieldName);
2354   if (!R || !R->getValue())
2355     PrintFatalError(getLoc(), "Record `" + getName() +
2356       "' does not have a field named `" + FieldName + "'!\n");
2357 
2358   if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
2359     return II->getValue();
2360   PrintFatalError(getLoc(), Twine("Record `") + getName() + "', field `" +
2361                                 FieldName +
2362                                 "' exists but does not have an int value: " +
2363                                 R->getValue()->getAsString());
2364 }
2365 
2366 std::vector<int64_t>
2367 Record::getValueAsListOfInts(StringRef FieldName) const {
2368   ListInit *List = getValueAsListInit(FieldName);
2369   std::vector<int64_t> Ints;
2370   for (Init *I : List->getValues()) {
2371     if (IntInit *II = dyn_cast<IntInit>(I))
2372       Ints.push_back(II->getValue());
2373     else
2374       PrintFatalError(getLoc(),
2375                       Twine("Record `") + getName() + "', field `" + FieldName +
2376                           "' exists but does not have a list of ints value: " +
2377                           I->getAsString());
2378   }
2379   return Ints;
2380 }
2381 
2382 std::vector<StringRef>
2383 Record::getValueAsListOfStrings(StringRef FieldName) const {
2384   ListInit *List = getValueAsListInit(FieldName);
2385   std::vector<StringRef> Strings;
2386   for (Init *I : List->getValues()) {
2387     if (StringInit *SI = dyn_cast<StringInit>(I))
2388       Strings.push_back(SI->getValue());
2389     else if (CodeInit *CI = dyn_cast<CodeInit>(I))
2390       Strings.push_back(CI->getValue());
2391     else
2392       PrintFatalError(getLoc(),
2393                       Twine("Record `") + getName() + "', field `" + FieldName +
2394                           "' exists but does not have a list of strings value: " +
2395                           I->getAsString());
2396   }
2397   return Strings;
2398 }
2399 
2400 Record *Record::getValueAsDef(StringRef FieldName) const {
2401   const RecordVal *R = getValue(FieldName);
2402   if (!R || !R->getValue())
2403     PrintFatalError(getLoc(), "Record `" + getName() +
2404       "' does not have a field named `" + FieldName + "'!\n");
2405 
2406   if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
2407     return DI->getDef();
2408   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2409     FieldName + "' does not have a def initializer!");
2410 }
2411 
2412 Record *Record::getValueAsOptionalDef(StringRef FieldName) const {
2413   const RecordVal *R = getValue(FieldName);
2414   if (!R || !R->getValue())
2415     PrintFatalError(getLoc(), "Record `" + getName() +
2416       "' does not have a field named `" + FieldName + "'!\n");
2417 
2418   if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
2419     return DI->getDef();
2420   if (isa<UnsetInit>(R->getValue()))
2421     return nullptr;
2422   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2423     FieldName + "' does not have either a def initializer or '?'!");
2424 }
2425 
2426 
2427 bool Record::getValueAsBit(StringRef FieldName) const {
2428   const RecordVal *R = getValue(FieldName);
2429   if (!R || !R->getValue())
2430     PrintFatalError(getLoc(), "Record `" + getName() +
2431       "' does not have a field named `" + FieldName + "'!\n");
2432 
2433   if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
2434     return BI->getValue();
2435   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2436     FieldName + "' does not have a bit initializer!");
2437 }
2438 
2439 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
2440   const RecordVal *R = getValue(FieldName);
2441   if (!R || !R->getValue())
2442     PrintFatalError(getLoc(), "Record `" + getName() +
2443       "' does not have a field named `" + FieldName.str() + "'!\n");
2444 
2445   if (isa<UnsetInit>(R->getValue())) {
2446     Unset = true;
2447     return false;
2448   }
2449   Unset = false;
2450   if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
2451     return BI->getValue();
2452   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2453     FieldName + "' does not have a bit initializer!");
2454 }
2455 
2456 DagInit *Record::getValueAsDag(StringRef FieldName) const {
2457   const RecordVal *R = getValue(FieldName);
2458   if (!R || !R->getValue())
2459     PrintFatalError(getLoc(), "Record `" + getName() +
2460       "' does not have a field named `" + FieldName + "'!\n");
2461 
2462   if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
2463     return DI;
2464   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2465     FieldName + "' does not have a dag initializer!");
2466 }
2467 
2468 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2469 LLVM_DUMP_METHOD void RecordKeeper::dump() const { errs() << *this; }
2470 #endif
2471 
2472 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
2473   OS << "------------- Classes -----------------\n";
2474   for (const auto &C : RK.getClasses())
2475     OS << "class " << *C.second;
2476 
2477   OS << "------------- Defs -----------------\n";
2478   for (const auto &D : RK.getDefs())
2479     OS << "def " << *D.second;
2480   return OS;
2481 }
2482 
2483 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
2484 /// an identifier.
2485 Init *RecordKeeper::getNewAnonymousName() {
2486   return StringInit::get("anonymous_" + utostr(AnonCounter++));
2487 }
2488 
2489 std::vector<Record *> RecordKeeper::getAllDerivedDefinitions(
2490     const ArrayRef<StringRef> ClassNames) const {
2491   SmallVector<Record *, 2> ClassRecs;
2492   std::vector<Record *> Defs;
2493 
2494   assert(ClassNames.size() > 0 && "At least one class must be passed.");
2495   for (const auto &ClassName : ClassNames) {
2496     Record *Class = getClass(ClassName);
2497     if (!Class)
2498       PrintFatalError("The class '" + ClassName + "' is not defined\n");
2499     ClassRecs.push_back(Class);
2500   }
2501 
2502   for (const auto &OneDef : getDefs()) {
2503     if (all_of(ClassRecs, [&OneDef](const Record *Class) {
2504                             return OneDef.second->isSubClassOf(Class);
2505                           }))
2506       Defs.push_back(OneDef.second.get());
2507   }
2508 
2509   return Defs;
2510 }
2511 
2512 Init *MapResolver::resolve(Init *VarName) {
2513   auto It = Map.find(VarName);
2514   if (It == Map.end())
2515     return nullptr;
2516 
2517   Init *I = It->second.V;
2518 
2519   if (!It->second.Resolved && Map.size() > 1) {
2520     // Resolve mutual references among the mapped variables, but prevent
2521     // infinite recursion.
2522     Map.erase(It);
2523     I = I->resolveReferences(*this);
2524     Map[VarName] = {I, true};
2525   }
2526 
2527   return I;
2528 }
2529 
2530 Init *RecordResolver::resolve(Init *VarName) {
2531   Init *Val = Cache.lookup(VarName);
2532   if (Val)
2533     return Val;
2534 
2535   for (Init *S : Stack) {
2536     if (S == VarName)
2537       return nullptr; // prevent infinite recursion
2538   }
2539 
2540   if (RecordVal *RV = getCurrentRecord()->getValue(VarName)) {
2541     if (!isa<UnsetInit>(RV->getValue())) {
2542       Val = RV->getValue();
2543       Stack.push_back(VarName);
2544       Val = Val->resolveReferences(*this);
2545       Stack.pop_back();
2546     }
2547   }
2548 
2549   Cache[VarName] = Val;
2550   return Val;
2551 }
2552 
2553 Init *TrackUnresolvedResolver::resolve(Init *VarName) {
2554   Init *I = nullptr;
2555 
2556   if (R) {
2557     I = R->resolve(VarName);
2558     if (I && !FoundUnresolved) {
2559       // Do not recurse into the resolved initializer, as that would change
2560       // the behavior of the resolver we're delegating, but do check to see
2561       // if there are unresolved variables remaining.
2562       TrackUnresolvedResolver Sub;
2563       I->resolveReferences(Sub);
2564       FoundUnresolved |= Sub.FoundUnresolved;
2565     }
2566   }
2567 
2568   if (!I)
2569     FoundUnresolved = true;
2570   return I;
2571 }
2572 
2573 Init *HasReferenceResolver::resolve(Init *VarName)
2574 {
2575   if (VarName == VarNameToTrack)
2576     Found = true;
2577   return nullptr;
2578 }
2579