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