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/TableGen/Record.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/FoldingSet.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/Config/llvm-config.h"
23 #include "llvm/Support/Allocator.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/SMLoc.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/TableGen/Error.h"
30 #include <cassert>
31 #include <cstdint>
32 #include <map>
33 #include <memory>
34 #include <string>
35 #include <utility>
36 #include <vector>
37 
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "tblgen-records"
41 
42 //===----------------------------------------------------------------------===//
43 //    Context
44 //===----------------------------------------------------------------------===//
45 
46 namespace llvm {
47 namespace detail {
48 /// This class represents the internal implementation of the RecordKeeper.
49 /// It contains all of the contextual static state of the Record classes. It is
50 /// kept out-of-line to simplify dependencies, and also make it easier for
51 /// internal classes to access the uniquer state of the keeper.
52 struct RecordKeeperImpl {
53   RecordKeeperImpl(RecordKeeper &RK)
54       : SharedBitRecTy(RK), SharedIntRecTy(RK), SharedStringRecTy(RK),
55         SharedDagRecTy(RK), AnyRecord(RK, 0), TheUnsetInit(RK),
56         TrueBitInit(true, &SharedBitRecTy),
57         FalseBitInit(false, &SharedBitRecTy), StringInitStringPool(Allocator),
58         StringInitCodePool(Allocator), AnonCounter(0), LastRecordID(0) {}
59 
60   BumpPtrAllocator Allocator;
61   std::vector<BitsRecTy *> SharedBitsRecTys;
62   BitRecTy SharedBitRecTy;
63   IntRecTy SharedIntRecTy;
64   StringRecTy SharedStringRecTy;
65   DagRecTy SharedDagRecTy;
66 
67   RecordRecTy AnyRecord;
68   UnsetInit TheUnsetInit;
69   BitInit TrueBitInit;
70   BitInit FalseBitInit;
71 
72   FoldingSet<BitsInit> TheBitsInitPool;
73   std::map<int64_t, IntInit *> TheIntInitPool;
74   StringMap<StringInit *, BumpPtrAllocator &> StringInitStringPool;
75   StringMap<StringInit *, BumpPtrAllocator &> StringInitCodePool;
76   FoldingSet<ListInit> TheListInitPool;
77   FoldingSet<UnOpInit> TheUnOpInitPool;
78   FoldingSet<BinOpInit> TheBinOpInitPool;
79   FoldingSet<TernOpInit> TheTernOpInitPool;
80   FoldingSet<FoldOpInit> TheFoldOpInitPool;
81   FoldingSet<IsAOpInit> TheIsAOpInitPool;
82   FoldingSet<ExistsOpInit> TheExistsOpInitPool;
83   DenseMap<std::pair<RecTy *, Init *>, VarInit *> TheVarInitPool;
84   DenseMap<std::pair<TypedInit *, unsigned>, VarBitInit *> TheVarBitInitPool;
85   DenseMap<std::pair<TypedInit *, unsigned>, VarListElementInit *>
86       TheVarListElementInitPool;
87   FoldingSet<VarDefInit> TheVarDefInitPool;
88   DenseMap<std::pair<Init *, StringInit *>, FieldInit *> TheFieldInitPool;
89   FoldingSet<CondOpInit> TheCondOpInitPool;
90   FoldingSet<DagInit> TheDagInitPool;
91   FoldingSet<RecordRecTy> RecordTypePool;
92 
93   unsigned AnonCounter;
94   unsigned LastRecordID;
95 };
96 } // namespace detail
97 } // namespace llvm
98 
99 //===----------------------------------------------------------------------===//
100 //    Type implementations
101 //===----------------------------------------------------------------------===//
102 
103 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
104 LLVM_DUMP_METHOD void RecTy::dump() const { print(errs()); }
105 #endif
106 
107 ListRecTy *RecTy::getListTy() {
108   if (!ListTy)
109     ListTy = new (RK.getImpl().Allocator) ListRecTy(this);
110   return ListTy;
111 }
112 
113 bool RecTy::typeIsConvertibleTo(const RecTy *RHS) const {
114   assert(RHS && "NULL pointer");
115   return Kind == RHS->getRecTyKind();
116 }
117 
118 bool RecTy::typeIsA(const RecTy *RHS) const { return this == RHS; }
119 
120 BitRecTy *BitRecTy::get(RecordKeeper &RK) {
121   return &RK.getImpl().SharedBitRecTy;
122 }
123 
124 bool BitRecTy::typeIsConvertibleTo(const RecTy *RHS) const{
125   if (RecTy::typeIsConvertibleTo(RHS) || RHS->getRecTyKind() == IntRecTyKind)
126     return true;
127   if (const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
128     return BitsTy->getNumBits() == 1;
129   return false;
130 }
131 
132 BitsRecTy *BitsRecTy::get(RecordKeeper &RK, unsigned Sz) {
133   detail::RecordKeeperImpl &RKImpl = RK.getImpl();
134   if (Sz >= RKImpl.SharedBitsRecTys.size())
135     RKImpl.SharedBitsRecTys.resize(Sz + 1);
136   BitsRecTy *&Ty = RKImpl.SharedBitsRecTys[Sz];
137   if (!Ty)
138     Ty = new (RKImpl.Allocator) BitsRecTy(RK, Sz);
139   return Ty;
140 }
141 
142 std::string BitsRecTy::getAsString() const {
143   return "bits<" + utostr(Size) + ">";
144 }
145 
146 bool BitsRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
147   if (RecTy::typeIsConvertibleTo(RHS)) //argument and the sender are same type
148     return cast<BitsRecTy>(RHS)->Size == Size;
149   RecTyKind kind = RHS->getRecTyKind();
150   return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
151 }
152 
153 bool BitsRecTy::typeIsA(const RecTy *RHS) const {
154   if (const BitsRecTy *RHSb = dyn_cast<BitsRecTy>(RHS))
155     return RHSb->Size == Size;
156   return false;
157 }
158 
159 IntRecTy *IntRecTy::get(RecordKeeper &RK) {
160   return &RK.getImpl().SharedIntRecTy;
161 }
162 
163 bool IntRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
164   RecTyKind kind = RHS->getRecTyKind();
165   return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
166 }
167 
168 StringRecTy *StringRecTy::get(RecordKeeper &RK) {
169   return &RK.getImpl().SharedStringRecTy;
170 }
171 
172 std::string StringRecTy::getAsString() const {
173   return "string";
174 }
175 
176 bool StringRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
177   RecTyKind Kind = RHS->getRecTyKind();
178   return Kind == StringRecTyKind;
179 }
180 
181 std::string ListRecTy::getAsString() const {
182   return "list<" + ElementTy->getAsString() + ">";
183 }
184 
185 bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
186   if (const auto *ListTy = dyn_cast<ListRecTy>(RHS))
187     return ElementTy->typeIsConvertibleTo(ListTy->getElementType());
188   return false;
189 }
190 
191 bool ListRecTy::typeIsA(const RecTy *RHS) const {
192   if (const ListRecTy *RHSl = dyn_cast<ListRecTy>(RHS))
193     return getElementType()->typeIsA(RHSl->getElementType());
194   return false;
195 }
196 
197 DagRecTy *DagRecTy::get(RecordKeeper &RK) {
198   return &RK.getImpl().SharedDagRecTy;
199 }
200 
201 std::string DagRecTy::getAsString() const {
202   return "dag";
203 }
204 
205 static void ProfileRecordRecTy(FoldingSetNodeID &ID,
206                                ArrayRef<Record *> Classes) {
207   ID.AddInteger(Classes.size());
208   for (Record *R : Classes)
209     ID.AddPointer(R);
210 }
211 
212 RecordRecTy *RecordRecTy::get(RecordKeeper &RK,
213                               ArrayRef<Record *> UnsortedClasses) {
214   detail::RecordKeeperImpl &RKImpl = RK.getImpl();
215   if (UnsortedClasses.empty())
216     return &RKImpl.AnyRecord;
217 
218   FoldingSet<RecordRecTy> &ThePool = RKImpl.RecordTypePool;
219 
220   SmallVector<Record *, 4> Classes(UnsortedClasses.begin(),
221                                    UnsortedClasses.end());
222   llvm::sort(Classes, [](Record *LHS, Record *RHS) {
223     return LHS->getNameInitAsString() < RHS->getNameInitAsString();
224   });
225 
226   FoldingSetNodeID ID;
227   ProfileRecordRecTy(ID, Classes);
228 
229   void *IP = nullptr;
230   if (RecordRecTy *Ty = ThePool.FindNodeOrInsertPos(ID, IP))
231     return Ty;
232 
233 #ifndef NDEBUG
234   // Check for redundancy.
235   for (unsigned i = 0; i < Classes.size(); ++i) {
236     for (unsigned j = 0; j < Classes.size(); ++j) {
237       assert(i == j || !Classes[i]->isSubClassOf(Classes[j]));
238     }
239     assert(&Classes[0]->getRecords() == &Classes[i]->getRecords());
240   }
241 #endif
242 
243   void *Mem = RKImpl.Allocator.Allocate(
244       totalSizeToAlloc<Record *>(Classes.size()), alignof(RecordRecTy));
245   RecordRecTy *Ty = new (Mem) RecordRecTy(RK, Classes.size());
246   std::uninitialized_copy(Classes.begin(), Classes.end(),
247                           Ty->getTrailingObjects<Record *>());
248   ThePool.InsertNode(Ty, IP);
249   return Ty;
250 }
251 RecordRecTy *RecordRecTy::get(Record *Class) {
252   assert(Class && "unexpected null class");
253   return get(Class->getRecords(), Class);
254 }
255 
256 void RecordRecTy::Profile(FoldingSetNodeID &ID) const {
257   ProfileRecordRecTy(ID, getClasses());
258 }
259 
260 std::string RecordRecTy::getAsString() const {
261   if (NumClasses == 1)
262     return getClasses()[0]->getNameInitAsString();
263 
264   std::string Str = "{";
265   bool First = true;
266   for (Record *R : getClasses()) {
267     if (!First)
268       Str += ", ";
269     First = false;
270     Str += R->getNameInitAsString();
271   }
272   Str += "}";
273   return Str;
274 }
275 
276 bool RecordRecTy::isSubClassOf(Record *Class) const {
277   return llvm::any_of(getClasses(), [Class](Record *MySuperClass) {
278                                       return MySuperClass == Class ||
279                                              MySuperClass->isSubClassOf(Class);
280                                     });
281 }
282 
283 bool RecordRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
284   if (this == RHS)
285     return true;
286 
287   const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
288   if (!RTy)
289     return false;
290 
291   return llvm::all_of(RTy->getClasses(), [this](Record *TargetClass) {
292                                            return isSubClassOf(TargetClass);
293                                          });
294 }
295 
296 bool RecordRecTy::typeIsA(const RecTy *RHS) const {
297   return typeIsConvertibleTo(RHS);
298 }
299 
300 static RecordRecTy *resolveRecordTypes(RecordRecTy *T1, RecordRecTy *T2) {
301   SmallVector<Record *, 4> CommonSuperClasses;
302   SmallVector<Record *, 4> Stack(T1->classes_begin(), T1->classes_end());
303 
304   while (!Stack.empty()) {
305     Record *R = Stack.pop_back_val();
306 
307     if (T2->isSubClassOf(R)) {
308       CommonSuperClasses.push_back(R);
309     } else {
310       R->getDirectSuperClasses(Stack);
311     }
312   }
313 
314   return RecordRecTy::get(T1->getRecordKeeper(), CommonSuperClasses);
315 }
316 
317 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
318   if (T1 == T2)
319     return T1;
320 
321   if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
322     if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2))
323       return resolveRecordTypes(RecTy1, RecTy2);
324   }
325 
326   if (T1->typeIsConvertibleTo(T2))
327     return T2;
328   if (T2->typeIsConvertibleTo(T1))
329     return T1;
330 
331   if (ListRecTy *ListTy1 = dyn_cast<ListRecTy>(T1)) {
332     if (ListRecTy *ListTy2 = dyn_cast<ListRecTy>(T2)) {
333       RecTy* NewType = resolveTypes(ListTy1->getElementType(),
334                                     ListTy2->getElementType());
335       if (NewType)
336         return NewType->getListTy();
337     }
338   }
339 
340   return nullptr;
341 }
342 
343 //===----------------------------------------------------------------------===//
344 //    Initializer implementations
345 //===----------------------------------------------------------------------===//
346 
347 void Init::anchor() {}
348 
349 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
350 LLVM_DUMP_METHOD void Init::dump() const { return print(errs()); }
351 #endif
352 
353 RecordKeeper &Init::getRecordKeeper() const {
354   if (auto *TyInit = dyn_cast<TypedInit>(this))
355     return TyInit->getType()->getRecordKeeper();
356   return cast<UnsetInit>(this)->getRecordKeeper();
357 }
358 
359 UnsetInit *UnsetInit::get(RecordKeeper &RK) {
360   return &RK.getImpl().TheUnsetInit;
361 }
362 
363 Init *UnsetInit::getCastTo(RecTy *Ty) const {
364   return const_cast<UnsetInit *>(this);
365 }
366 
367 Init *UnsetInit::convertInitializerTo(RecTy *Ty) const {
368   return const_cast<UnsetInit *>(this);
369 }
370 
371 BitInit *BitInit::get(RecordKeeper &RK, bool V) {
372   return V ? &RK.getImpl().TrueBitInit : &RK.getImpl().FalseBitInit;
373 }
374 
375 Init *BitInit::convertInitializerTo(RecTy *Ty) const {
376   if (isa<BitRecTy>(Ty))
377     return const_cast<BitInit *>(this);
378 
379   if (isa<IntRecTy>(Ty))
380     return IntInit::get(getRecordKeeper(), getValue());
381 
382   if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
383     // Can only convert single bit.
384     if (BRT->getNumBits() == 1)
385       return BitsInit::get(getRecordKeeper(), const_cast<BitInit *>(this));
386   }
387 
388   return nullptr;
389 }
390 
391 static void
392 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
393   ID.AddInteger(Range.size());
394 
395   for (Init *I : Range)
396     ID.AddPointer(I);
397 }
398 
399 BitsInit *BitsInit::get(RecordKeeper &RK, ArrayRef<Init *> Range) {
400   FoldingSetNodeID ID;
401   ProfileBitsInit(ID, Range);
402 
403   detail::RecordKeeperImpl &RKImpl = RK.getImpl();
404   void *IP = nullptr;
405   if (BitsInit *I = RKImpl.TheBitsInitPool.FindNodeOrInsertPos(ID, IP))
406     return I;
407 
408   void *Mem = RKImpl.Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),
409                                         alignof(BitsInit));
410   BitsInit *I = new (Mem) BitsInit(RK, Range.size());
411   std::uninitialized_copy(Range.begin(), Range.end(),
412                           I->getTrailingObjects<Init *>());
413   RKImpl.TheBitsInitPool.InsertNode(I, IP);
414   return I;
415 }
416 
417 void BitsInit::Profile(FoldingSetNodeID &ID) const {
418   ProfileBitsInit(ID, makeArrayRef(getTrailingObjects<Init *>(), NumBits));
419 }
420 
421 Init *BitsInit::convertInitializerTo(RecTy *Ty) const {
422   if (isa<BitRecTy>(Ty)) {
423     if (getNumBits() != 1) return nullptr; // Only accept if just one bit!
424     return getBit(0);
425   }
426 
427   if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
428     // If the number of bits is right, return it.  Otherwise we need to expand
429     // or truncate.
430     if (getNumBits() != BRT->getNumBits()) return nullptr;
431     return const_cast<BitsInit *>(this);
432   }
433 
434   if (isa<IntRecTy>(Ty)) {
435     int64_t Result = 0;
436     for (unsigned i = 0, e = getNumBits(); i != e; ++i)
437       if (auto *Bit = dyn_cast<BitInit>(getBit(i)))
438         Result |= static_cast<int64_t>(Bit->getValue()) << i;
439       else
440         return nullptr;
441     return IntInit::get(getRecordKeeper(), Result);
442   }
443 
444   return nullptr;
445 }
446 
447 Init *
448 BitsInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
449   SmallVector<Init *, 16> NewBits(Bits.size());
450 
451   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
452     if (Bits[i] >= getNumBits())
453       return nullptr;
454     NewBits[i] = getBit(Bits[i]);
455   }
456   return BitsInit::get(getRecordKeeper(), NewBits);
457 }
458 
459 bool BitsInit::isConcrete() const {
460   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
461     if (!getBit(i)->isConcrete())
462       return false;
463   }
464   return true;
465 }
466 
467 std::string BitsInit::getAsString() const {
468   std::string Result = "{ ";
469   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
470     if (i) Result += ", ";
471     if (Init *Bit = getBit(e-i-1))
472       Result += Bit->getAsString();
473     else
474       Result += "*";
475   }
476   return Result + " }";
477 }
478 
479 // resolveReferences - If there are any field references that refer to fields
480 // that have been filled in, we can propagate the values now.
481 Init *BitsInit::resolveReferences(Resolver &R) const {
482   bool Changed = false;
483   SmallVector<Init *, 16> NewBits(getNumBits());
484 
485   Init *CachedBitVarRef = nullptr;
486   Init *CachedBitVarResolved = nullptr;
487 
488   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
489     Init *CurBit = getBit(i);
490     Init *NewBit = CurBit;
491 
492     if (VarBitInit *CurBitVar = dyn_cast<VarBitInit>(CurBit)) {
493       if (CurBitVar->getBitVar() != CachedBitVarRef) {
494         CachedBitVarRef = CurBitVar->getBitVar();
495         CachedBitVarResolved = CachedBitVarRef->resolveReferences(R);
496       }
497       assert(CachedBitVarResolved && "Unresolved bitvar reference");
498       NewBit = CachedBitVarResolved->getBit(CurBitVar->getBitNum());
499     } else {
500       // getBit(0) implicitly converts int and bits<1> values to bit.
501       NewBit = CurBit->resolveReferences(R)->getBit(0);
502     }
503 
504     if (isa<UnsetInit>(NewBit) && R.keepUnsetBits())
505       NewBit = CurBit;
506     NewBits[i] = NewBit;
507     Changed |= CurBit != NewBit;
508   }
509 
510   if (Changed)
511     return BitsInit::get(getRecordKeeper(), NewBits);
512 
513   return const_cast<BitsInit *>(this);
514 }
515 
516 IntInit *IntInit::get(RecordKeeper &RK, int64_t V) {
517   IntInit *&I = RK.getImpl().TheIntInitPool[V];
518   if (!I)
519     I = new (RK.getImpl().Allocator) IntInit(RK, V);
520   return I;
521 }
522 
523 std::string IntInit::getAsString() const {
524   return itostr(Value);
525 }
526 
527 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
528   // For example, with NumBits == 4, we permit Values from [-7 .. 15].
529   return (NumBits >= sizeof(Value) * 8) ||
530          (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
531 }
532 
533 Init *IntInit::convertInitializerTo(RecTy *Ty) const {
534   if (isa<IntRecTy>(Ty))
535     return const_cast<IntInit *>(this);
536 
537   if (isa<BitRecTy>(Ty)) {
538     int64_t Val = getValue();
539     if (Val != 0 && Val != 1) return nullptr;  // Only accept 0 or 1 for a bit!
540     return BitInit::get(getRecordKeeper(), Val != 0);
541   }
542 
543   if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
544     int64_t Value = getValue();
545     // Make sure this bitfield is large enough to hold the integer value.
546     if (!canFitInBitfield(Value, BRT->getNumBits()))
547       return nullptr;
548 
549     SmallVector<Init *, 16> NewBits(BRT->getNumBits());
550     for (unsigned i = 0; i != BRT->getNumBits(); ++i)
551       NewBits[i] =
552           BitInit::get(getRecordKeeper(), Value & ((i < 64) ? (1LL << i) : 0));
553 
554     return BitsInit::get(getRecordKeeper(), NewBits);
555   }
556 
557   return nullptr;
558 }
559 
560 Init *
561 IntInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
562   SmallVector<Init *, 16> NewBits(Bits.size());
563 
564   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
565     if (Bits[i] >= 64)
566       return nullptr;
567 
568     NewBits[i] =
569         BitInit::get(getRecordKeeper(), Value & (INT64_C(1) << Bits[i]));
570   }
571   return BitsInit::get(getRecordKeeper(), NewBits);
572 }
573 
574 AnonymousNameInit *AnonymousNameInit::get(RecordKeeper &RK, unsigned V) {
575   return new (RK.getImpl().Allocator) AnonymousNameInit(RK, V);
576 }
577 
578 StringInit *AnonymousNameInit::getNameInit() const {
579   return StringInit::get(getRecordKeeper(), getAsString());
580 }
581 
582 std::string AnonymousNameInit::getAsString() const {
583   return "anonymous_" + utostr(Value);
584 }
585 
586 Init *AnonymousNameInit::resolveReferences(Resolver &R) const {
587   auto *Old = const_cast<Init *>(static_cast<const Init *>(this));
588   auto *New = R.resolve(Old);
589   New = New ? New : Old;
590   if (R.isFinal())
591     if (auto *Anonymous = dyn_cast<AnonymousNameInit>(New))
592       return Anonymous->getNameInit();
593   return New;
594 }
595 
596 StringInit *StringInit::get(RecordKeeper &RK, StringRef V, StringFormat Fmt) {
597   detail::RecordKeeperImpl &RKImpl = RK.getImpl();
598   auto &InitMap = Fmt == SF_String ? RKImpl.StringInitStringPool
599                                    : RKImpl.StringInitCodePool;
600   auto &Entry = *InitMap.insert(std::make_pair(V, nullptr)).first;
601   if (!Entry.second)
602     Entry.second = new (RKImpl.Allocator) StringInit(RK, Entry.getKey(), Fmt);
603   return Entry.second;
604 }
605 
606 Init *StringInit::convertInitializerTo(RecTy *Ty) const {
607   if (isa<StringRecTy>(Ty))
608     return const_cast<StringInit *>(this);
609 
610   return nullptr;
611 }
612 
613 static void ProfileListInit(FoldingSetNodeID &ID,
614                             ArrayRef<Init *> Range,
615                             RecTy *EltTy) {
616   ID.AddInteger(Range.size());
617   ID.AddPointer(EltTy);
618 
619   for (Init *I : Range)
620     ID.AddPointer(I);
621 }
622 
623 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
624   FoldingSetNodeID ID;
625   ProfileListInit(ID, Range, EltTy);
626 
627   detail::RecordKeeperImpl &RK = EltTy->getRecordKeeper().getImpl();
628   void *IP = nullptr;
629   if (ListInit *I = RK.TheListInitPool.FindNodeOrInsertPos(ID, IP))
630     return I;
631 
632   assert(Range.empty() || !isa<TypedInit>(Range[0]) ||
633          cast<TypedInit>(Range[0])->getType()->typeIsConvertibleTo(EltTy));
634 
635   void *Mem = RK.Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),
636                                     alignof(ListInit));
637   ListInit *I = new (Mem) ListInit(Range.size(), EltTy);
638   std::uninitialized_copy(Range.begin(), Range.end(),
639                           I->getTrailingObjects<Init *>());
640   RK.TheListInitPool.InsertNode(I, IP);
641   return I;
642 }
643 
644 void ListInit::Profile(FoldingSetNodeID &ID) const {
645   RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
646 
647   ProfileListInit(ID, getValues(), EltTy);
648 }
649 
650 Init *ListInit::convertInitializerTo(RecTy *Ty) const {
651   if (getType() == Ty)
652     return const_cast<ListInit*>(this);
653 
654   if (auto *LRT = dyn_cast<ListRecTy>(Ty)) {
655     SmallVector<Init*, 8> Elements;
656     Elements.reserve(getValues().size());
657 
658     // Verify that all of the elements of the list are subclasses of the
659     // appropriate class!
660     bool Changed = false;
661     RecTy *ElementType = LRT->getElementType();
662     for (Init *I : getValues())
663       if (Init *CI = I->convertInitializerTo(ElementType)) {
664         Elements.push_back(CI);
665         if (CI != I)
666           Changed = true;
667       } else
668         return nullptr;
669 
670     if (!Changed)
671       return const_cast<ListInit*>(this);
672     return ListInit::get(Elements, ElementType);
673   }
674 
675   return nullptr;
676 }
677 
678 Init *ListInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
679   if (Elements.size() == 1) {
680     if (Elements[0] >= size())
681       return nullptr;
682     return getElement(Elements[0]);
683   }
684 
685   SmallVector<Init*, 8> Vals;
686   Vals.reserve(Elements.size());
687   for (unsigned Element : Elements) {
688     if (Element >= size())
689       return nullptr;
690     Vals.push_back(getElement(Element));
691   }
692   return ListInit::get(Vals, getElementType());
693 }
694 
695 Record *ListInit::getElementAsRecord(unsigned i) const {
696   assert(i < NumValues && "List element index out of range!");
697   DefInit *DI = dyn_cast<DefInit>(getElement(i));
698   if (!DI)
699     PrintFatalError("Expected record in list!");
700   return DI->getDef();
701 }
702 
703 Init *ListInit::resolveReferences(Resolver &R) const {
704   SmallVector<Init*, 8> Resolved;
705   Resolved.reserve(size());
706   bool Changed = false;
707 
708   for (Init *CurElt : getValues()) {
709     Init *E = CurElt->resolveReferences(R);
710     Changed |= E != CurElt;
711     Resolved.push_back(E);
712   }
713 
714   if (Changed)
715     return ListInit::get(Resolved, getElementType());
716   return const_cast<ListInit *>(this);
717 }
718 
719 bool ListInit::isComplete() const {
720   for (Init *Element : *this) {
721     if (!Element->isComplete())
722       return false;
723   }
724   return true;
725 }
726 
727 bool ListInit::isConcrete() const {
728   for (Init *Element : *this) {
729     if (!Element->isConcrete())
730       return false;
731   }
732   return true;
733 }
734 
735 std::string ListInit::getAsString() const {
736   std::string Result = "[";
737   const char *sep = "";
738   for (Init *Element : *this) {
739     Result += sep;
740     sep = ", ";
741     Result += Element->getAsString();
742   }
743   return Result + "]";
744 }
745 
746 Init *OpInit::getBit(unsigned Bit) const {
747   if (getType() == BitRecTy::get(getRecordKeeper()))
748     return const_cast<OpInit*>(this);
749   return VarBitInit::get(const_cast<OpInit*>(this), Bit);
750 }
751 
752 static void
753 ProfileUnOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *Op, RecTy *Type) {
754   ID.AddInteger(Opcode);
755   ID.AddPointer(Op);
756   ID.AddPointer(Type);
757 }
758 
759 UnOpInit *UnOpInit::get(UnaryOp Opc, Init *LHS, RecTy *Type) {
760   FoldingSetNodeID ID;
761   ProfileUnOpInit(ID, Opc, LHS, Type);
762 
763   detail::RecordKeeperImpl &RK = Type->getRecordKeeper().getImpl();
764   void *IP = nullptr;
765   if (UnOpInit *I = RK.TheUnOpInitPool.FindNodeOrInsertPos(ID, IP))
766     return I;
767 
768   UnOpInit *I = new (RK.Allocator) UnOpInit(Opc, LHS, Type);
769   RK.TheUnOpInitPool.InsertNode(I, IP);
770   return I;
771 }
772 
773 void UnOpInit::Profile(FoldingSetNodeID &ID) const {
774   ProfileUnOpInit(ID, getOpcode(), getOperand(), getType());
775 }
776 
777 Init *UnOpInit::Fold(Record *CurRec, bool IsFinal) const {
778   RecordKeeper &RK = getRecordKeeper();
779   switch (getOpcode()) {
780   case CAST:
781     if (isa<StringRecTy>(getType())) {
782       if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
783         return LHSs;
784 
785       if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
786         return StringInit::get(RK, LHSd->getAsString());
787 
788       if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
789               LHS->convertInitializerTo(IntRecTy::get(RK))))
790         return StringInit::get(RK, LHSi->getAsString());
791 
792     } else if (isa<RecordRecTy>(getType())) {
793       if (StringInit *Name = dyn_cast<StringInit>(LHS)) {
794         if (!CurRec && !IsFinal)
795           break;
796         assert(CurRec && "NULL pointer");
797         Record *D;
798 
799         // Self-references are allowed, but their resolution is delayed until
800         // the final resolve to ensure that we get the correct type for them.
801         auto *Anonymous = dyn_cast<AnonymousNameInit>(CurRec->getNameInit());
802         if (Name == CurRec->getNameInit() ||
803             (Anonymous && Name == Anonymous->getNameInit())) {
804           if (!IsFinal)
805             break;
806           D = CurRec;
807         } else {
808           D = CurRec->getRecords().getDef(Name->getValue());
809           if (!D) {
810             if (IsFinal)
811               PrintFatalError(CurRec->getLoc(),
812                               Twine("Undefined reference to record: '") +
813                               Name->getValue() + "'\n");
814             break;
815           }
816         }
817 
818         DefInit *DI = DefInit::get(D);
819         if (!DI->getType()->typeIsA(getType())) {
820           PrintFatalError(CurRec->getLoc(),
821                           Twine("Expected type '") +
822                           getType()->getAsString() + "', got '" +
823                           DI->getType()->getAsString() + "' in: " +
824                           getAsString() + "\n");
825         }
826         return DI;
827       }
828     }
829 
830     if (Init *NewInit = LHS->convertInitializerTo(getType()))
831       return NewInit;
832     break;
833 
834   case NOT:
835     if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
836             LHS->convertInitializerTo(IntRecTy::get(RK))))
837       return IntInit::get(RK, LHSi->getValue() ? 0 : 1);
838     break;
839 
840   case HEAD:
841     if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
842       assert(!LHSl->empty() && "Empty list in head");
843       return LHSl->getElement(0);
844     }
845     break;
846 
847   case TAIL:
848     if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
849       assert(!LHSl->empty() && "Empty list in tail");
850       // Note the +1.  We can't just pass the result of getValues()
851       // directly.
852       return ListInit::get(LHSl->getValues().slice(1), LHSl->getElementType());
853     }
854     break;
855 
856   case SIZE:
857     if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
858       return IntInit::get(RK, LHSl->size());
859     if (DagInit *LHSd = dyn_cast<DagInit>(LHS))
860       return IntInit::get(RK, LHSd->arg_size());
861     if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
862       return IntInit::get(RK, LHSs->getValue().size());
863     break;
864 
865   case EMPTY:
866     if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
867       return IntInit::get(RK, LHSl->empty());
868     if (DagInit *LHSd = dyn_cast<DagInit>(LHS))
869       return IntInit::get(RK, LHSd->arg_empty());
870     if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
871       return IntInit::get(RK, LHSs->getValue().empty());
872     break;
873 
874   case GETDAGOP:
875     if (DagInit *Dag = dyn_cast<DagInit>(LHS)) {
876       DefInit *DI = DefInit::get(Dag->getOperatorAsDef({}));
877       if (!DI->getType()->typeIsA(getType())) {
878         PrintFatalError(CurRec->getLoc(),
879                         Twine("Expected type '") +
880                         getType()->getAsString() + "', got '" +
881                         DI->getType()->getAsString() + "' in: " +
882                         getAsString() + "\n");
883       } else {
884         return DI;
885       }
886     }
887     break;
888   }
889   return const_cast<UnOpInit *>(this);
890 }
891 
892 Init *UnOpInit::resolveReferences(Resolver &R) const {
893   Init *lhs = LHS->resolveReferences(R);
894 
895   if (LHS != lhs || (R.isFinal() && getOpcode() == CAST))
896     return (UnOpInit::get(getOpcode(), lhs, getType()))
897         ->Fold(R.getCurrentRecord(), R.isFinal());
898   return const_cast<UnOpInit *>(this);
899 }
900 
901 std::string UnOpInit::getAsString() const {
902   std::string Result;
903   switch (getOpcode()) {
904   case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
905   case NOT: Result = "!not"; break;
906   case HEAD: Result = "!head"; break;
907   case TAIL: Result = "!tail"; break;
908   case SIZE: Result = "!size"; break;
909   case EMPTY: Result = "!empty"; break;
910   case GETDAGOP: Result = "!getdagop"; break;
911   }
912   return Result + "(" + LHS->getAsString() + ")";
913 }
914 
915 static void
916 ProfileBinOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *RHS,
917                  RecTy *Type) {
918   ID.AddInteger(Opcode);
919   ID.AddPointer(LHS);
920   ID.AddPointer(RHS);
921   ID.AddPointer(Type);
922 }
923 
924 BinOpInit *BinOpInit::get(BinaryOp Opc, Init *LHS, Init *RHS, RecTy *Type) {
925   FoldingSetNodeID ID;
926   ProfileBinOpInit(ID, Opc, LHS, RHS, Type);
927 
928   detail::RecordKeeperImpl &RK = LHS->getRecordKeeper().getImpl();
929   void *IP = nullptr;
930   if (BinOpInit *I = RK.TheBinOpInitPool.FindNodeOrInsertPos(ID, IP))
931     return I;
932 
933   BinOpInit *I = new (RK.Allocator) BinOpInit(Opc, LHS, RHS, Type);
934   RK.TheBinOpInitPool.InsertNode(I, IP);
935   return I;
936 }
937 
938 void BinOpInit::Profile(FoldingSetNodeID &ID) const {
939   ProfileBinOpInit(ID, getOpcode(), getLHS(), getRHS(), getType());
940 }
941 
942 static StringInit *ConcatStringInits(const StringInit *I0,
943                                      const StringInit *I1) {
944   SmallString<80> Concat(I0->getValue());
945   Concat.append(I1->getValue());
946   return StringInit::get(
947       I0->getRecordKeeper(), Concat,
948       StringInit::determineFormat(I0->getFormat(), I1->getFormat()));
949 }
950 
951 static StringInit *interleaveStringList(const ListInit *List,
952                                         const StringInit *Delim) {
953   if (List->size() == 0)
954     return StringInit::get(List->getRecordKeeper(), "");
955   StringInit *Element = dyn_cast<StringInit>(List->getElement(0));
956   if (!Element)
957     return nullptr;
958   SmallString<80> Result(Element->getValue());
959   StringInit::StringFormat Fmt = StringInit::SF_String;
960 
961   for (unsigned I = 1, E = List->size(); I < E; ++I) {
962     Result.append(Delim->getValue());
963     StringInit *Element = dyn_cast<StringInit>(List->getElement(I));
964     if (!Element)
965       return nullptr;
966     Result.append(Element->getValue());
967     Fmt = StringInit::determineFormat(Fmt, Element->getFormat());
968   }
969   return StringInit::get(List->getRecordKeeper(), Result, Fmt);
970 }
971 
972 static StringInit *interleaveIntList(const ListInit *List,
973                                      const StringInit *Delim) {
974   RecordKeeper &RK = List->getRecordKeeper();
975   if (List->size() == 0)
976     return StringInit::get(RK, "");
977   IntInit *Element = dyn_cast_or_null<IntInit>(
978       List->getElement(0)->convertInitializerTo(IntRecTy::get(RK)));
979   if (!Element)
980     return nullptr;
981   SmallString<80> Result(Element->getAsString());
982 
983   for (unsigned I = 1, E = List->size(); I < E; ++I) {
984     Result.append(Delim->getValue());
985     IntInit *Element = dyn_cast_or_null<IntInit>(
986         List->getElement(I)->convertInitializerTo(IntRecTy::get(RK)));
987     if (!Element)
988       return nullptr;
989     Result.append(Element->getAsString());
990   }
991   return StringInit::get(RK, Result);
992 }
993 
994 Init *BinOpInit::getStrConcat(Init *I0, Init *I1) {
995   // Shortcut for the common case of concatenating two strings.
996   if (const StringInit *I0s = dyn_cast<StringInit>(I0))
997     if (const StringInit *I1s = dyn_cast<StringInit>(I1))
998       return ConcatStringInits(I0s, I1s);
999   return BinOpInit::get(BinOpInit::STRCONCAT, I0, I1,
1000                         StringRecTy::get(I0->getRecordKeeper()));
1001 }
1002 
1003 static ListInit *ConcatListInits(const ListInit *LHS,
1004                                  const ListInit *RHS) {
1005   SmallVector<Init *, 8> Args;
1006   llvm::append_range(Args, *LHS);
1007   llvm::append_range(Args, *RHS);
1008   return ListInit::get(Args, LHS->getElementType());
1009 }
1010 
1011 Init *BinOpInit::getListConcat(TypedInit *LHS, Init *RHS) {
1012   assert(isa<ListRecTy>(LHS->getType()) && "First arg must be a list");
1013 
1014   // Shortcut for the common case of concatenating two lists.
1015    if (const ListInit *LHSList = dyn_cast<ListInit>(LHS))
1016      if (const ListInit *RHSList = dyn_cast<ListInit>(RHS))
1017        return ConcatListInits(LHSList, RHSList);
1018    return BinOpInit::get(BinOpInit::LISTCONCAT, LHS, RHS, LHS->getType());
1019 }
1020 
1021 Init *BinOpInit::Fold(Record *CurRec) const {
1022   switch (getOpcode()) {
1023   case CONCAT: {
1024     DagInit *LHSs = dyn_cast<DagInit>(LHS);
1025     DagInit *RHSs = dyn_cast<DagInit>(RHS);
1026     if (LHSs && RHSs) {
1027       DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
1028       DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
1029       if ((!LOp && !isa<UnsetInit>(LHSs->getOperator())) ||
1030           (!ROp && !isa<UnsetInit>(RHSs->getOperator())))
1031         break;
1032       if (LOp && ROp && LOp->getDef() != ROp->getDef()) {
1033         PrintFatalError(Twine("Concatenated Dag operators do not match: '") +
1034                         LHSs->getAsString() + "' vs. '" + RHSs->getAsString() +
1035                         "'");
1036       }
1037       Init *Op = LOp ? LOp : ROp;
1038       if (!Op)
1039         Op = UnsetInit::get(getRecordKeeper());
1040 
1041       SmallVector<Init*, 8> Args;
1042       SmallVector<StringInit*, 8> ArgNames;
1043       for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
1044         Args.push_back(LHSs->getArg(i));
1045         ArgNames.push_back(LHSs->getArgName(i));
1046       }
1047       for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
1048         Args.push_back(RHSs->getArg(i));
1049         ArgNames.push_back(RHSs->getArgName(i));
1050       }
1051       return DagInit::get(Op, nullptr, Args, ArgNames);
1052     }
1053     break;
1054   }
1055   case LISTCONCAT: {
1056     ListInit *LHSs = dyn_cast<ListInit>(LHS);
1057     ListInit *RHSs = dyn_cast<ListInit>(RHS);
1058     if (LHSs && RHSs) {
1059       SmallVector<Init *, 8> Args;
1060       llvm::append_range(Args, *LHSs);
1061       llvm::append_range(Args, *RHSs);
1062       return ListInit::get(Args, LHSs->getElementType());
1063     }
1064     break;
1065   }
1066   case LISTSPLAT: {
1067     TypedInit *Value = dyn_cast<TypedInit>(LHS);
1068     IntInit *Size = dyn_cast<IntInit>(RHS);
1069     if (Value && Size) {
1070       SmallVector<Init *, 8> Args(Size->getValue(), Value);
1071       return ListInit::get(Args, Value->getType());
1072     }
1073     break;
1074   }
1075   case STRCONCAT: {
1076     StringInit *LHSs = dyn_cast<StringInit>(LHS);
1077     StringInit *RHSs = dyn_cast<StringInit>(RHS);
1078     if (LHSs && RHSs)
1079       return ConcatStringInits(LHSs, RHSs);
1080     break;
1081   }
1082   case INTERLEAVE: {
1083     ListInit *List = dyn_cast<ListInit>(LHS);
1084     StringInit *Delim = dyn_cast<StringInit>(RHS);
1085     if (List && Delim) {
1086       StringInit *Result;
1087       if (isa<StringRecTy>(List->getElementType()))
1088         Result = interleaveStringList(List, Delim);
1089       else
1090         Result = interleaveIntList(List, Delim);
1091       if (Result)
1092         return Result;
1093     }
1094     break;
1095   }
1096   case EQ:
1097   case NE:
1098   case LE:
1099   case LT:
1100   case GE:
1101   case GT: {
1102     // First see if we have two bit, bits, or int.
1103     IntInit *LHSi = dyn_cast_or_null<IntInit>(
1104         LHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
1105     IntInit *RHSi = dyn_cast_or_null<IntInit>(
1106         RHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
1107 
1108     if (LHSi && RHSi) {
1109       bool Result;
1110       switch (getOpcode()) {
1111       case EQ: Result = LHSi->getValue() == RHSi->getValue(); break;
1112       case NE: Result = LHSi->getValue() != RHSi->getValue(); break;
1113       case LE: Result = LHSi->getValue() <= RHSi->getValue(); break;
1114       case LT: Result = LHSi->getValue() <  RHSi->getValue(); break;
1115       case GE: Result = LHSi->getValue() >= RHSi->getValue(); break;
1116       case GT: Result = LHSi->getValue() >  RHSi->getValue(); break;
1117       default: llvm_unreachable("unhandled comparison");
1118       }
1119       return BitInit::get(getRecordKeeper(), Result);
1120     }
1121 
1122     // Next try strings.
1123     StringInit *LHSs = dyn_cast<StringInit>(LHS);
1124     StringInit *RHSs = dyn_cast<StringInit>(RHS);
1125 
1126     if (LHSs && RHSs) {
1127       bool Result;
1128       switch (getOpcode()) {
1129       case EQ: Result = LHSs->getValue() == RHSs->getValue(); break;
1130       case NE: Result = LHSs->getValue() != RHSs->getValue(); break;
1131       case LE: Result = LHSs->getValue() <= RHSs->getValue(); break;
1132       case LT: Result = LHSs->getValue() <  RHSs->getValue(); break;
1133       case GE: Result = LHSs->getValue() >= RHSs->getValue(); break;
1134       case GT: Result = LHSs->getValue() >  RHSs->getValue(); break;
1135       default: llvm_unreachable("unhandled comparison");
1136       }
1137       return BitInit::get(getRecordKeeper(), Result);
1138     }
1139 
1140     // Finally, !eq and !ne can be used with records.
1141     if (getOpcode() == EQ || getOpcode() == NE) {
1142       DefInit *LHSd = dyn_cast<DefInit>(LHS);
1143       DefInit *RHSd = dyn_cast<DefInit>(RHS);
1144       if (LHSd && RHSd)
1145         return BitInit::get(getRecordKeeper(),
1146                             (getOpcode() == EQ) ? LHSd == RHSd : LHSd != RHSd);
1147     }
1148 
1149     break;
1150   }
1151   case SETDAGOP: {
1152     DagInit *Dag = dyn_cast<DagInit>(LHS);
1153     DefInit *Op = dyn_cast<DefInit>(RHS);
1154     if (Dag && Op) {
1155       SmallVector<Init*, 8> Args;
1156       SmallVector<StringInit*, 8> ArgNames;
1157       for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1158         Args.push_back(Dag->getArg(i));
1159         ArgNames.push_back(Dag->getArgName(i));
1160       }
1161       return DagInit::get(Op, nullptr, Args, ArgNames);
1162     }
1163     break;
1164   }
1165   case ADD:
1166   case SUB:
1167   case MUL:
1168   case AND:
1169   case OR:
1170   case XOR:
1171   case SHL:
1172   case SRA:
1173   case SRL: {
1174     IntInit *LHSi = dyn_cast_or_null<IntInit>(
1175         LHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
1176     IntInit *RHSi = dyn_cast_or_null<IntInit>(
1177         RHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
1178     if (LHSi && RHSi) {
1179       int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
1180       int64_t Result;
1181       switch (getOpcode()) {
1182       default: llvm_unreachable("Bad opcode!");
1183       case ADD: Result = LHSv + RHSv; break;
1184       case SUB: Result = LHSv - RHSv; break;
1185       case MUL: Result = LHSv * RHSv; break;
1186       case AND: Result = LHSv & RHSv; break;
1187       case OR:  Result = LHSv | RHSv; break;
1188       case XOR: Result = LHSv ^ RHSv; break;
1189       case SHL: Result = (uint64_t)LHSv << (uint64_t)RHSv; break;
1190       case SRA: Result = LHSv >> RHSv; break;
1191       case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
1192       }
1193       return IntInit::get(getRecordKeeper(), Result);
1194     }
1195     break;
1196   }
1197   }
1198   return const_cast<BinOpInit *>(this);
1199 }
1200 
1201 Init *BinOpInit::resolveReferences(Resolver &R) const {
1202   Init *lhs = LHS->resolveReferences(R);
1203   Init *rhs = RHS->resolveReferences(R);
1204 
1205   if (LHS != lhs || RHS != rhs)
1206     return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))
1207         ->Fold(R.getCurrentRecord());
1208   return const_cast<BinOpInit *>(this);
1209 }
1210 
1211 std::string BinOpInit::getAsString() const {
1212   std::string Result;
1213   switch (getOpcode()) {
1214   case CONCAT: Result = "!con"; break;
1215   case ADD: Result = "!add"; break;
1216   case SUB: Result = "!sub"; break;
1217   case MUL: Result = "!mul"; break;
1218   case AND: Result = "!and"; break;
1219   case OR: Result = "!or"; break;
1220   case XOR: Result = "!xor"; break;
1221   case SHL: Result = "!shl"; break;
1222   case SRA: Result = "!sra"; break;
1223   case SRL: Result = "!srl"; break;
1224   case EQ: Result = "!eq"; break;
1225   case NE: Result = "!ne"; break;
1226   case LE: Result = "!le"; break;
1227   case LT: Result = "!lt"; break;
1228   case GE: Result = "!ge"; break;
1229   case GT: Result = "!gt"; break;
1230   case LISTCONCAT: Result = "!listconcat"; break;
1231   case LISTSPLAT: Result = "!listsplat"; break;
1232   case STRCONCAT: Result = "!strconcat"; break;
1233   case INTERLEAVE: Result = "!interleave"; break;
1234   case SETDAGOP: Result = "!setdagop"; break;
1235   }
1236   return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
1237 }
1238 
1239 static void
1240 ProfileTernOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *MHS,
1241                   Init *RHS, RecTy *Type) {
1242   ID.AddInteger(Opcode);
1243   ID.AddPointer(LHS);
1244   ID.AddPointer(MHS);
1245   ID.AddPointer(RHS);
1246   ID.AddPointer(Type);
1247 }
1248 
1249 TernOpInit *TernOpInit::get(TernaryOp Opc, Init *LHS, Init *MHS, Init *RHS,
1250                             RecTy *Type) {
1251   FoldingSetNodeID ID;
1252   ProfileTernOpInit(ID, Opc, LHS, MHS, RHS, Type);
1253 
1254   detail::RecordKeeperImpl &RK = LHS->getRecordKeeper().getImpl();
1255   void *IP = nullptr;
1256   if (TernOpInit *I = RK.TheTernOpInitPool.FindNodeOrInsertPos(ID, IP))
1257     return I;
1258 
1259   TernOpInit *I = new (RK.Allocator) TernOpInit(Opc, LHS, MHS, RHS, Type);
1260   RK.TheTernOpInitPool.InsertNode(I, IP);
1261   return I;
1262 }
1263 
1264 void TernOpInit::Profile(FoldingSetNodeID &ID) const {
1265   ProfileTernOpInit(ID, getOpcode(), getLHS(), getMHS(), getRHS(), getType());
1266 }
1267 
1268 static Init *ItemApply(Init *LHS, Init *MHSe, Init *RHS, Record *CurRec) {
1269   MapResolver R(CurRec);
1270   R.set(LHS, MHSe);
1271   return RHS->resolveReferences(R);
1272 }
1273 
1274 static Init *ForeachDagApply(Init *LHS, DagInit *MHSd, Init *RHS,
1275                              Record *CurRec) {
1276   bool Change = false;
1277   Init *Val = ItemApply(LHS, MHSd->getOperator(), RHS, CurRec);
1278   if (Val != MHSd->getOperator())
1279     Change = true;
1280 
1281   SmallVector<std::pair<Init *, StringInit *>, 8> NewArgs;
1282   for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1283     Init *Arg = MHSd->getArg(i);
1284     Init *NewArg;
1285     StringInit *ArgName = MHSd->getArgName(i);
1286 
1287     if (DagInit *Argd = dyn_cast<DagInit>(Arg))
1288       NewArg = ForeachDagApply(LHS, Argd, RHS, CurRec);
1289     else
1290       NewArg = ItemApply(LHS, Arg, RHS, CurRec);
1291 
1292     NewArgs.push_back(std::make_pair(NewArg, ArgName));
1293     if (Arg != NewArg)
1294       Change = true;
1295   }
1296 
1297   if (Change)
1298     return DagInit::get(Val, nullptr, NewArgs);
1299   return MHSd;
1300 }
1301 
1302 // Applies RHS to all elements of MHS, using LHS as a temp variable.
1303 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1304                            Record *CurRec) {
1305   if (DagInit *MHSd = dyn_cast<DagInit>(MHS))
1306     return ForeachDagApply(LHS, MHSd, RHS, CurRec);
1307 
1308   if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) {
1309     SmallVector<Init *, 8> NewList(MHSl->begin(), MHSl->end());
1310 
1311     for (Init *&Item : NewList) {
1312       Init *NewItem = ItemApply(LHS, Item, RHS, CurRec);
1313       if (NewItem != Item)
1314         Item = NewItem;
1315     }
1316     return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
1317   }
1318 
1319   return nullptr;
1320 }
1321 
1322 // Evaluates RHS for all elements of MHS, using LHS as a temp variable.
1323 // Creates a new list with the elements that evaluated to true.
1324 static Init *FilterHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1325                           Record *CurRec) {
1326   if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) {
1327     SmallVector<Init *, 8> NewList;
1328 
1329     for (Init *Item : MHSl->getValues()) {
1330       Init *Include = ItemApply(LHS, Item, RHS, CurRec);
1331       if (!Include)
1332         return nullptr;
1333       if (IntInit *IncludeInt =
1334               dyn_cast_or_null<IntInit>(Include->convertInitializerTo(
1335                   IntRecTy::get(LHS->getRecordKeeper())))) {
1336         if (IncludeInt->getValue())
1337           NewList.push_back(Item);
1338       } else {
1339         return nullptr;
1340       }
1341     }
1342     return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
1343   }
1344 
1345   return nullptr;
1346 }
1347 
1348 Init *TernOpInit::Fold(Record *CurRec) const {
1349   RecordKeeper &RK = getRecordKeeper();
1350   switch (getOpcode()) {
1351   case SUBST: {
1352     DefInit *LHSd = dyn_cast<DefInit>(LHS);
1353     VarInit *LHSv = dyn_cast<VarInit>(LHS);
1354     StringInit *LHSs = dyn_cast<StringInit>(LHS);
1355 
1356     DefInit *MHSd = dyn_cast<DefInit>(MHS);
1357     VarInit *MHSv = dyn_cast<VarInit>(MHS);
1358     StringInit *MHSs = dyn_cast<StringInit>(MHS);
1359 
1360     DefInit *RHSd = dyn_cast<DefInit>(RHS);
1361     VarInit *RHSv = dyn_cast<VarInit>(RHS);
1362     StringInit *RHSs = dyn_cast<StringInit>(RHS);
1363 
1364     if (LHSd && MHSd && RHSd) {
1365       Record *Val = RHSd->getDef();
1366       if (LHSd->getAsString() == RHSd->getAsString())
1367         Val = MHSd->getDef();
1368       return DefInit::get(Val);
1369     }
1370     if (LHSv && MHSv && RHSv) {
1371       std::string Val = std::string(RHSv->getName());
1372       if (LHSv->getAsString() == RHSv->getAsString())
1373         Val = std::string(MHSv->getName());
1374       return VarInit::get(Val, getType());
1375     }
1376     if (LHSs && MHSs && RHSs) {
1377       std::string Val = std::string(RHSs->getValue());
1378 
1379       std::string::size_type found;
1380       std::string::size_type idx = 0;
1381       while (true) {
1382         found = Val.find(std::string(LHSs->getValue()), idx);
1383         if (found == std::string::npos)
1384           break;
1385         Val.replace(found, LHSs->getValue().size(),
1386                     std::string(MHSs->getValue()));
1387         idx = found + MHSs->getValue().size();
1388       }
1389 
1390       return StringInit::get(RK, Val);
1391     }
1392     break;
1393   }
1394 
1395   case FOREACH: {
1396     if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(), CurRec))
1397       return Result;
1398     break;
1399   }
1400 
1401   case FILTER: {
1402     if (Init *Result = FilterHelper(LHS, MHS, RHS, getType(), CurRec))
1403       return Result;
1404     break;
1405   }
1406 
1407   case IF: {
1408     if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
1409             LHS->convertInitializerTo(IntRecTy::get(RK)))) {
1410       if (LHSi->getValue())
1411         return MHS;
1412       return RHS;
1413     }
1414     break;
1415   }
1416 
1417   case DAG: {
1418     ListInit *MHSl = dyn_cast<ListInit>(MHS);
1419     ListInit *RHSl = dyn_cast<ListInit>(RHS);
1420     bool MHSok = MHSl || isa<UnsetInit>(MHS);
1421     bool RHSok = RHSl || isa<UnsetInit>(RHS);
1422 
1423     if (isa<UnsetInit>(MHS) && isa<UnsetInit>(RHS))
1424       break; // Typically prevented by the parser, but might happen with template args
1425 
1426     if (MHSok && RHSok && (!MHSl || !RHSl || MHSl->size() == RHSl->size())) {
1427       SmallVector<std::pair<Init *, StringInit *>, 8> Children;
1428       unsigned Size = MHSl ? MHSl->size() : RHSl->size();
1429       for (unsigned i = 0; i != Size; ++i) {
1430         Init *Node = MHSl ? MHSl->getElement(i) : UnsetInit::get(RK);
1431         Init *Name = RHSl ? RHSl->getElement(i) : UnsetInit::get(RK);
1432         if (!isa<StringInit>(Name) && !isa<UnsetInit>(Name))
1433           return const_cast<TernOpInit *>(this);
1434         Children.emplace_back(Node, dyn_cast<StringInit>(Name));
1435       }
1436       return DagInit::get(LHS, nullptr, Children);
1437     }
1438     break;
1439   }
1440 
1441   case SUBSTR: {
1442     StringInit *LHSs = dyn_cast<StringInit>(LHS);
1443     IntInit *MHSi = dyn_cast<IntInit>(MHS);
1444     IntInit *RHSi = dyn_cast<IntInit>(RHS);
1445     if (LHSs && MHSi && RHSi) {
1446       int64_t StringSize = LHSs->getValue().size();
1447       int64_t Start = MHSi->getValue();
1448       int64_t Length = RHSi->getValue();
1449       if (Start < 0 || Start > StringSize)
1450         PrintError(CurRec->getLoc(),
1451                    Twine("!substr start position is out of range 0...") +
1452                        std::to_string(StringSize) + ": " +
1453                        std::to_string(Start));
1454       if (Length < 0)
1455         PrintError(CurRec->getLoc(), "!substr length must be nonnegative");
1456       return StringInit::get(RK, LHSs->getValue().substr(Start, Length),
1457                              LHSs->getFormat());
1458     }
1459     break;
1460   }
1461 
1462   case FIND: {
1463     StringInit *LHSs = dyn_cast<StringInit>(LHS);
1464     StringInit *MHSs = dyn_cast<StringInit>(MHS);
1465     IntInit *RHSi = dyn_cast<IntInit>(RHS);
1466     if (LHSs && MHSs && RHSi) {
1467       int64_t SourceSize = LHSs->getValue().size();
1468       int64_t Start = RHSi->getValue();
1469       if (Start < 0 || Start > SourceSize)
1470         PrintError(CurRec->getLoc(),
1471                    Twine("!find start position is out of range 0...") +
1472                        std::to_string(SourceSize) + ": " +
1473                        std::to_string(Start));
1474       auto I = LHSs->getValue().find(MHSs->getValue(), Start);
1475       if (I == std::string::npos)
1476         return IntInit::get(RK, -1);
1477       return IntInit::get(RK, I);
1478     }
1479     break;
1480   }
1481   }
1482 
1483   return const_cast<TernOpInit *>(this);
1484 }
1485 
1486 Init *TernOpInit::resolveReferences(Resolver &R) const {
1487   Init *lhs = LHS->resolveReferences(R);
1488 
1489   if (getOpcode() == IF && lhs != LHS) {
1490     if (IntInit *Value = dyn_cast_or_null<IntInit>(
1491             lhs->convertInitializerTo(IntRecTy::get(getRecordKeeper())))) {
1492       // Short-circuit
1493       if (Value->getValue())
1494         return MHS->resolveReferences(R);
1495       return RHS->resolveReferences(R);
1496     }
1497   }
1498 
1499   Init *mhs = MHS->resolveReferences(R);
1500   Init *rhs;
1501 
1502   if (getOpcode() == FOREACH || getOpcode() == FILTER) {
1503     ShadowResolver SR(R);
1504     SR.addShadow(lhs);
1505     rhs = RHS->resolveReferences(SR);
1506   } else {
1507     rhs = RHS->resolveReferences(R);
1508   }
1509 
1510   if (LHS != lhs || MHS != mhs || RHS != rhs)
1511     return (TernOpInit::get(getOpcode(), lhs, mhs, rhs, getType()))
1512         ->Fold(R.getCurrentRecord());
1513   return const_cast<TernOpInit *>(this);
1514 }
1515 
1516 std::string TernOpInit::getAsString() const {
1517   std::string Result;
1518   bool UnquotedLHS = false;
1519   switch (getOpcode()) {
1520   case DAG: Result = "!dag"; break;
1521   case FILTER: Result = "!filter"; UnquotedLHS = true; break;
1522   case FOREACH: Result = "!foreach"; UnquotedLHS = true; break;
1523   case IF: Result = "!if"; break;
1524   case SUBST: Result = "!subst"; break;
1525   case SUBSTR: Result = "!substr"; break;
1526   case FIND: Result = "!find"; break;
1527   }
1528   return (Result + "(" +
1529           (UnquotedLHS ? LHS->getAsUnquotedString() : LHS->getAsString()) +
1530           ", " + MHS->getAsString() + ", " + RHS->getAsString() + ")");
1531 }
1532 
1533 static void ProfileFoldOpInit(FoldingSetNodeID &ID, Init *Start, Init *List,
1534                               Init *A, Init *B, Init *Expr, RecTy *Type) {
1535   ID.AddPointer(Start);
1536   ID.AddPointer(List);
1537   ID.AddPointer(A);
1538   ID.AddPointer(B);
1539   ID.AddPointer(Expr);
1540   ID.AddPointer(Type);
1541 }
1542 
1543 FoldOpInit *FoldOpInit::get(Init *Start, Init *List, Init *A, Init *B,
1544                             Init *Expr, RecTy *Type) {
1545   FoldingSetNodeID ID;
1546   ProfileFoldOpInit(ID, Start, List, A, B, Expr, Type);
1547 
1548   detail::RecordKeeperImpl &RK = Start->getRecordKeeper().getImpl();
1549   void *IP = nullptr;
1550   if (FoldOpInit *I = RK.TheFoldOpInitPool.FindNodeOrInsertPos(ID, IP))
1551     return I;
1552 
1553   FoldOpInit *I = new (RK.Allocator) FoldOpInit(Start, List, A, B, Expr, Type);
1554   RK.TheFoldOpInitPool.InsertNode(I, IP);
1555   return I;
1556 }
1557 
1558 void FoldOpInit::Profile(FoldingSetNodeID &ID) const {
1559   ProfileFoldOpInit(ID, Start, List, A, B, Expr, getType());
1560 }
1561 
1562 Init *FoldOpInit::Fold(Record *CurRec) const {
1563   if (ListInit *LI = dyn_cast<ListInit>(List)) {
1564     Init *Accum = Start;
1565     for (Init *Elt : *LI) {
1566       MapResolver R(CurRec);
1567       R.set(A, Accum);
1568       R.set(B, Elt);
1569       Accum = Expr->resolveReferences(R);
1570     }
1571     return Accum;
1572   }
1573   return const_cast<FoldOpInit *>(this);
1574 }
1575 
1576 Init *FoldOpInit::resolveReferences(Resolver &R) const {
1577   Init *NewStart = Start->resolveReferences(R);
1578   Init *NewList = List->resolveReferences(R);
1579   ShadowResolver SR(R);
1580   SR.addShadow(A);
1581   SR.addShadow(B);
1582   Init *NewExpr = Expr->resolveReferences(SR);
1583 
1584   if (Start == NewStart && List == NewList && Expr == NewExpr)
1585     return const_cast<FoldOpInit *>(this);
1586 
1587   return get(NewStart, NewList, A, B, NewExpr, getType())
1588       ->Fold(R.getCurrentRecord());
1589 }
1590 
1591 Init *FoldOpInit::getBit(unsigned Bit) const {
1592   return VarBitInit::get(const_cast<FoldOpInit *>(this), Bit);
1593 }
1594 
1595 std::string FoldOpInit::getAsString() const {
1596   return (Twine("!foldl(") + Start->getAsString() + ", " + List->getAsString() +
1597           ", " + A->getAsUnquotedString() + ", " + B->getAsUnquotedString() +
1598           ", " + Expr->getAsString() + ")")
1599       .str();
1600 }
1601 
1602 static void ProfileIsAOpInit(FoldingSetNodeID &ID, RecTy *CheckType,
1603                              Init *Expr) {
1604   ID.AddPointer(CheckType);
1605   ID.AddPointer(Expr);
1606 }
1607 
1608 IsAOpInit *IsAOpInit::get(RecTy *CheckType, Init *Expr) {
1609 
1610   FoldingSetNodeID ID;
1611   ProfileIsAOpInit(ID, CheckType, Expr);
1612 
1613   detail::RecordKeeperImpl &RK = Expr->getRecordKeeper().getImpl();
1614   void *IP = nullptr;
1615   if (IsAOpInit *I = RK.TheIsAOpInitPool.FindNodeOrInsertPos(ID, IP))
1616     return I;
1617 
1618   IsAOpInit *I = new (RK.Allocator) IsAOpInit(CheckType, Expr);
1619   RK.TheIsAOpInitPool.InsertNode(I, IP);
1620   return I;
1621 }
1622 
1623 void IsAOpInit::Profile(FoldingSetNodeID &ID) const {
1624   ProfileIsAOpInit(ID, CheckType, Expr);
1625 }
1626 
1627 Init *IsAOpInit::Fold() const {
1628   if (TypedInit *TI = dyn_cast<TypedInit>(Expr)) {
1629     // Is the expression type known to be (a subclass of) the desired type?
1630     if (TI->getType()->typeIsConvertibleTo(CheckType))
1631       return IntInit::get(getRecordKeeper(), 1);
1632 
1633     if (isa<RecordRecTy>(CheckType)) {
1634       // If the target type is not a subclass of the expression type, or if
1635       // the expression has fully resolved to a record, we know that it can't
1636       // be of the required type.
1637       if (!CheckType->typeIsConvertibleTo(TI->getType()) || isa<DefInit>(Expr))
1638         return IntInit::get(getRecordKeeper(), 0);
1639     } else {
1640       // We treat non-record types as not castable.
1641       return IntInit::get(getRecordKeeper(), 0);
1642     }
1643   }
1644   return const_cast<IsAOpInit *>(this);
1645 }
1646 
1647 Init *IsAOpInit::resolveReferences(Resolver &R) const {
1648   Init *NewExpr = Expr->resolveReferences(R);
1649   if (Expr != NewExpr)
1650     return get(CheckType, NewExpr)->Fold();
1651   return const_cast<IsAOpInit *>(this);
1652 }
1653 
1654 Init *IsAOpInit::getBit(unsigned Bit) const {
1655   return VarBitInit::get(const_cast<IsAOpInit *>(this), Bit);
1656 }
1657 
1658 std::string IsAOpInit::getAsString() const {
1659   return (Twine("!isa<") + CheckType->getAsString() + ">(" +
1660           Expr->getAsString() + ")")
1661       .str();
1662 }
1663 
1664 static void ProfileExistsOpInit(FoldingSetNodeID &ID, RecTy *CheckType,
1665                                 Init *Expr) {
1666   ID.AddPointer(CheckType);
1667   ID.AddPointer(Expr);
1668 }
1669 
1670 ExistsOpInit *ExistsOpInit::get(RecTy *CheckType, Init *Expr) {
1671   FoldingSetNodeID ID;
1672   ProfileExistsOpInit(ID, CheckType, Expr);
1673 
1674   detail::RecordKeeperImpl &RK = Expr->getRecordKeeper().getImpl();
1675   void *IP = nullptr;
1676   if (ExistsOpInit *I = RK.TheExistsOpInitPool.FindNodeOrInsertPos(ID, IP))
1677     return I;
1678 
1679   ExistsOpInit *I = new (RK.Allocator) ExistsOpInit(CheckType, Expr);
1680   RK.TheExistsOpInitPool.InsertNode(I, IP);
1681   return I;
1682 }
1683 
1684 void ExistsOpInit::Profile(FoldingSetNodeID &ID) const {
1685   ProfileExistsOpInit(ID, CheckType, Expr);
1686 }
1687 
1688 Init *ExistsOpInit::Fold(Record *CurRec, bool IsFinal) const {
1689   if (StringInit *Name = dyn_cast<StringInit>(Expr)) {
1690     if (!CurRec && !IsFinal)
1691       return const_cast<ExistsOpInit *>(this);
1692 
1693     // Self-references are allowed, but their resolution is delayed until
1694     // the final resolve to ensure that we get the correct type for them.
1695     auto *Anonymous = dyn_cast<AnonymousNameInit>(CurRec->getNameInit());
1696     if (Name == CurRec->getNameInit() ||
1697         (Anonymous && Name == Anonymous->getNameInit())) {
1698       if (!IsFinal)
1699         return const_cast<ExistsOpInit *>(this);
1700 
1701       // No doubt that there exists a record, so we should check if types are
1702       // compatiable.
1703       return IntInit::get(getRecordKeeper(),
1704                           CurRec->getType()->typeIsA(CheckType));
1705     }
1706 
1707     // Look up all defined records to see if we can find one.
1708     Record *D = CheckType->getRecordKeeper().getDef(Name->getValue());
1709     if (!D) {
1710       if (IsFinal)
1711         return IntInit::get(getRecordKeeper(), 0);
1712       return const_cast<ExistsOpInit *>(this);
1713     }
1714 
1715     // Check if types are compatiable.
1716     return IntInit::get(getRecordKeeper(),
1717                         DefInit::get(D)->getType()->typeIsA(CheckType));
1718   }
1719   return const_cast<ExistsOpInit *>(this);
1720 }
1721 
1722 Init *ExistsOpInit::resolveReferences(Resolver &R) const {
1723   Init *NewExpr = Expr->resolveReferences(R);
1724   if (Expr != NewExpr || R.isFinal())
1725     return get(CheckType, NewExpr)->Fold(R.getCurrentRecord(), R.isFinal());
1726   return const_cast<ExistsOpInit *>(this);
1727 }
1728 
1729 Init *ExistsOpInit::getBit(unsigned Bit) const {
1730   return VarBitInit::get(const_cast<ExistsOpInit *>(this), Bit);
1731 }
1732 
1733 std::string ExistsOpInit::getAsString() const {
1734   return (Twine("!exists<") + CheckType->getAsString() + ">(" +
1735           Expr->getAsString() + ")")
1736       .str();
1737 }
1738 
1739 RecTy *TypedInit::getFieldType(StringInit *FieldName) const {
1740   if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType())) {
1741     for (Record *Rec : RecordType->getClasses()) {
1742       if (RecordVal *Field = Rec->getValue(FieldName))
1743         return Field->getType();
1744     }
1745   }
1746   return nullptr;
1747 }
1748 
1749 Init *
1750 TypedInit::convertInitializerTo(RecTy *Ty) const {
1751   if (getType() == Ty || getType()->typeIsA(Ty))
1752     return const_cast<TypedInit *>(this);
1753 
1754   if (isa<BitRecTy>(getType()) && isa<BitsRecTy>(Ty) &&
1755       cast<BitsRecTy>(Ty)->getNumBits() == 1)
1756     return BitsInit::get(getRecordKeeper(), {const_cast<TypedInit *>(this)});
1757 
1758   return nullptr;
1759 }
1760 
1761 Init *TypedInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
1762   BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1763   if (!T) return nullptr;  // Cannot subscript a non-bits variable.
1764   unsigned NumBits = T->getNumBits();
1765 
1766   SmallVector<Init *, 16> NewBits;
1767   NewBits.reserve(Bits.size());
1768   for (unsigned Bit : Bits) {
1769     if (Bit >= NumBits)
1770       return nullptr;
1771 
1772     NewBits.push_back(VarBitInit::get(const_cast<TypedInit *>(this), Bit));
1773   }
1774   return BitsInit::get(getRecordKeeper(), NewBits);
1775 }
1776 
1777 Init *TypedInit::getCastTo(RecTy *Ty) const {
1778   // Handle the common case quickly
1779   if (getType() == Ty || getType()->typeIsA(Ty))
1780     return const_cast<TypedInit *>(this);
1781 
1782   if (Init *Converted = convertInitializerTo(Ty)) {
1783     assert(!isa<TypedInit>(Converted) ||
1784            cast<TypedInit>(Converted)->getType()->typeIsA(Ty));
1785     return Converted;
1786   }
1787 
1788   if (!getType()->typeIsConvertibleTo(Ty))
1789     return nullptr;
1790 
1791   return UnOpInit::get(UnOpInit::CAST, const_cast<TypedInit *>(this), Ty)
1792       ->Fold(nullptr);
1793 }
1794 
1795 Init *TypedInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
1796   ListRecTy *T = dyn_cast<ListRecTy>(getType());
1797   if (!T) return nullptr;  // Cannot subscript a non-list variable.
1798 
1799   if (Elements.size() == 1)
1800     return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1801 
1802   SmallVector<Init*, 8> ListInits;
1803   ListInits.reserve(Elements.size());
1804   for (unsigned Element : Elements)
1805     ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1806                                                 Element));
1807   return ListInit::get(ListInits, T->getElementType());
1808 }
1809 
1810 
1811 VarInit *VarInit::get(StringRef VN, RecTy *T) {
1812   Init *Value = StringInit::get(T->getRecordKeeper(), VN);
1813   return VarInit::get(Value, T);
1814 }
1815 
1816 VarInit *VarInit::get(Init *VN, RecTy *T) {
1817   detail::RecordKeeperImpl &RK = T->getRecordKeeper().getImpl();
1818   VarInit *&I = RK.TheVarInitPool[std::make_pair(T, VN)];
1819   if (!I)
1820     I = new (RK.Allocator) VarInit(VN, T);
1821   return I;
1822 }
1823 
1824 StringRef VarInit::getName() const {
1825   StringInit *NameString = cast<StringInit>(getNameInit());
1826   return NameString->getValue();
1827 }
1828 
1829 Init *VarInit::getBit(unsigned Bit) const {
1830   if (getType() == BitRecTy::get(getRecordKeeper()))
1831     return const_cast<VarInit*>(this);
1832   return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1833 }
1834 
1835 Init *VarInit::resolveReferences(Resolver &R) const {
1836   if (Init *Val = R.resolve(VarName))
1837     return Val;
1838   return const_cast<VarInit *>(this);
1839 }
1840 
1841 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1842   detail::RecordKeeperImpl &RK = T->getRecordKeeper().getImpl();
1843   VarBitInit *&I = RK.TheVarBitInitPool[std::make_pair(T, B)];
1844   if (!I)
1845     I = new (RK.Allocator) VarBitInit(T, B);
1846   return I;
1847 }
1848 
1849 std::string VarBitInit::getAsString() const {
1850   return TI->getAsString() + "{" + utostr(Bit) + "}";
1851 }
1852 
1853 Init *VarBitInit::resolveReferences(Resolver &R) const {
1854   Init *I = TI->resolveReferences(R);
1855   if (TI != I)
1856     return I->getBit(getBitNum());
1857 
1858   return const_cast<VarBitInit*>(this);
1859 }
1860 
1861 VarListElementInit *VarListElementInit::get(TypedInit *T, unsigned E) {
1862   detail::RecordKeeperImpl &RK = T->getRecordKeeper().getImpl();
1863   VarListElementInit *&I = RK.TheVarListElementInitPool[std::make_pair(T, E)];
1864   if (!I)
1865     I = new (RK.Allocator) VarListElementInit(T, E);
1866   return I;
1867 }
1868 
1869 std::string VarListElementInit::getAsString() const {
1870   return TI->getAsString() + "[" + utostr(Element) + "]";
1871 }
1872 
1873 Init *VarListElementInit::resolveReferences(Resolver &R) const {
1874   Init *NewTI = TI->resolveReferences(R);
1875   if (ListInit *List = dyn_cast<ListInit>(NewTI)) {
1876     // Leave out-of-bounds array references as-is. This can happen without
1877     // being an error, e.g. in the untaken "branch" of an !if expression.
1878     if (getElementNum() < List->size())
1879       return List->getElement(getElementNum());
1880   }
1881   if (NewTI != TI && isa<TypedInit>(NewTI))
1882     return VarListElementInit::get(cast<TypedInit>(NewTI), getElementNum());
1883   return const_cast<VarListElementInit *>(this);
1884 }
1885 
1886 Init *VarListElementInit::getBit(unsigned Bit) const {
1887   if (getType() == BitRecTy::get(getRecordKeeper()))
1888     return const_cast<VarListElementInit*>(this);
1889   return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1890 }
1891 
1892 DefInit::DefInit(Record *D)
1893     : TypedInit(IK_DefInit, D->getType()), Def(D) {}
1894 
1895 DefInit *DefInit::get(Record *R) {
1896   return R->getDefInit();
1897 }
1898 
1899 Init *DefInit::convertInitializerTo(RecTy *Ty) const {
1900   if (auto *RRT = dyn_cast<RecordRecTy>(Ty))
1901     if (getType()->typeIsConvertibleTo(RRT))
1902       return const_cast<DefInit *>(this);
1903   return nullptr;
1904 }
1905 
1906 RecTy *DefInit::getFieldType(StringInit *FieldName) const {
1907   if (const RecordVal *RV = Def->getValue(FieldName))
1908     return RV->getType();
1909   return nullptr;
1910 }
1911 
1912 std::string DefInit::getAsString() const { return std::string(Def->getName()); }
1913 
1914 static void ProfileVarDefInit(FoldingSetNodeID &ID,
1915                               Record *Class,
1916                               ArrayRef<Init *> Args) {
1917   ID.AddInteger(Args.size());
1918   ID.AddPointer(Class);
1919 
1920   for (Init *I : Args)
1921     ID.AddPointer(I);
1922 }
1923 
1924 VarDefInit::VarDefInit(Record *Class, unsigned N)
1925     : TypedInit(IK_VarDefInit, RecordRecTy::get(Class)), Class(Class),
1926       NumArgs(N) {}
1927 
1928 VarDefInit *VarDefInit::get(Record *Class, ArrayRef<Init *> Args) {
1929   FoldingSetNodeID ID;
1930   ProfileVarDefInit(ID, Class, Args);
1931 
1932   detail::RecordKeeperImpl &RK = Class->getRecords().getImpl();
1933   void *IP = nullptr;
1934   if (VarDefInit *I = RK.TheVarDefInitPool.FindNodeOrInsertPos(ID, IP))
1935     return I;
1936 
1937   void *Mem = RK.Allocator.Allocate(totalSizeToAlloc<Init *>(Args.size()),
1938                                     alignof(VarDefInit));
1939   VarDefInit *I = new (Mem) VarDefInit(Class, Args.size());
1940   std::uninitialized_copy(Args.begin(), Args.end(),
1941                           I->getTrailingObjects<Init *>());
1942   RK.TheVarDefInitPool.InsertNode(I, IP);
1943   return I;
1944 }
1945 
1946 void VarDefInit::Profile(FoldingSetNodeID &ID) const {
1947   ProfileVarDefInit(ID, Class, args());
1948 }
1949 
1950 DefInit *VarDefInit::instantiate() {
1951   if (!Def) {
1952     RecordKeeper &Records = Class->getRecords();
1953     auto NewRecOwner = std::make_unique<Record>(Records.getNewAnonymousName(),
1954                                            Class->getLoc(), Records,
1955                                            /*IsAnonymous=*/true);
1956     Record *NewRec = NewRecOwner.get();
1957 
1958     // Copy values from class to instance
1959     for (const RecordVal &Val : Class->getValues())
1960       NewRec->addValue(Val);
1961 
1962     // Copy assertions from class to instance.
1963     NewRec->appendAssertions(Class);
1964 
1965     // Substitute and resolve template arguments
1966     ArrayRef<Init *> TArgs = Class->getTemplateArgs();
1967     MapResolver R(NewRec);
1968 
1969     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1970       if (i < args_size())
1971         R.set(TArgs[i], getArg(i));
1972       else
1973         R.set(TArgs[i], NewRec->getValue(TArgs[i])->getValue());
1974 
1975       NewRec->removeValue(TArgs[i]);
1976     }
1977 
1978     NewRec->resolveReferences(R);
1979 
1980     // Add superclasses.
1981     ArrayRef<std::pair<Record *, SMRange>> SCs = Class->getSuperClasses();
1982     for (const auto &SCPair : SCs)
1983       NewRec->addSuperClass(SCPair.first, SCPair.second);
1984 
1985     NewRec->addSuperClass(Class,
1986                           SMRange(Class->getLoc().back(),
1987                                   Class->getLoc().back()));
1988 
1989     // Resolve internal references and store in record keeper
1990     NewRec->resolveReferences();
1991     Records.addDef(std::move(NewRecOwner));
1992 
1993     // Check the assertions.
1994     NewRec->checkRecordAssertions();
1995 
1996     Def = DefInit::get(NewRec);
1997   }
1998 
1999   return Def;
2000 }
2001 
2002 Init *VarDefInit::resolveReferences(Resolver &R) const {
2003   TrackUnresolvedResolver UR(&R);
2004   bool Changed = false;
2005   SmallVector<Init *, 8> NewArgs;
2006   NewArgs.reserve(args_size());
2007 
2008   for (Init *Arg : args()) {
2009     Init *NewArg = Arg->resolveReferences(UR);
2010     NewArgs.push_back(NewArg);
2011     Changed |= NewArg != Arg;
2012   }
2013 
2014   if (Changed) {
2015     auto New = VarDefInit::get(Class, NewArgs);
2016     if (!UR.foundUnresolved())
2017       return New->instantiate();
2018     return New;
2019   }
2020   return const_cast<VarDefInit *>(this);
2021 }
2022 
2023 Init *VarDefInit::Fold() const {
2024   if (Def)
2025     return Def;
2026 
2027   TrackUnresolvedResolver R;
2028   for (Init *Arg : args())
2029     Arg->resolveReferences(R);
2030 
2031   if (!R.foundUnresolved())
2032     return const_cast<VarDefInit *>(this)->instantiate();
2033   return const_cast<VarDefInit *>(this);
2034 }
2035 
2036 std::string VarDefInit::getAsString() const {
2037   std::string Result = Class->getNameInitAsString() + "<";
2038   const char *sep = "";
2039   for (Init *Arg : args()) {
2040     Result += sep;
2041     sep = ", ";
2042     Result += Arg->getAsString();
2043   }
2044   return Result + ">";
2045 }
2046 
2047 FieldInit *FieldInit::get(Init *R, StringInit *FN) {
2048   detail::RecordKeeperImpl &RK = R->getRecordKeeper().getImpl();
2049   FieldInit *&I = RK.TheFieldInitPool[std::make_pair(R, FN)];
2050   if (!I)
2051     I = new (RK.Allocator) FieldInit(R, FN);
2052   return I;
2053 }
2054 
2055 Init *FieldInit::getBit(unsigned Bit) const {
2056   if (getType() == BitRecTy::get(getRecordKeeper()))
2057     return const_cast<FieldInit*>(this);
2058   return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
2059 }
2060 
2061 Init *FieldInit::resolveReferences(Resolver &R) const {
2062   Init *NewRec = Rec->resolveReferences(R);
2063   if (NewRec != Rec)
2064     return FieldInit::get(NewRec, FieldName)->Fold(R.getCurrentRecord());
2065   return const_cast<FieldInit *>(this);
2066 }
2067 
2068 Init *FieldInit::Fold(Record *CurRec) const {
2069   if (DefInit *DI = dyn_cast<DefInit>(Rec)) {
2070     Record *Def = DI->getDef();
2071     if (Def == CurRec)
2072       PrintFatalError(CurRec->getLoc(),
2073                       Twine("Attempting to access field '") +
2074                       FieldName->getAsUnquotedString() + "' of '" +
2075                       Rec->getAsString() + "' is a forbidden self-reference");
2076     Init *FieldVal = Def->getValue(FieldName)->getValue();
2077     if (FieldVal->isConcrete())
2078       return FieldVal;
2079   }
2080   return const_cast<FieldInit *>(this);
2081 }
2082 
2083 bool FieldInit::isConcrete() const {
2084   if (DefInit *DI = dyn_cast<DefInit>(Rec)) {
2085     Init *FieldVal = DI->getDef()->getValue(FieldName)->getValue();
2086     return FieldVal->isConcrete();
2087   }
2088   return false;
2089 }
2090 
2091 static void ProfileCondOpInit(FoldingSetNodeID &ID,
2092                              ArrayRef<Init *> CondRange,
2093                              ArrayRef<Init *> ValRange,
2094                              const RecTy *ValType) {
2095   assert(CondRange.size() == ValRange.size() &&
2096          "Number of conditions and values must match!");
2097   ID.AddPointer(ValType);
2098   ArrayRef<Init *>::iterator Case = CondRange.begin();
2099   ArrayRef<Init *>::iterator Val = ValRange.begin();
2100 
2101   while (Case != CondRange.end()) {
2102     ID.AddPointer(*Case++);
2103     ID.AddPointer(*Val++);
2104   }
2105 }
2106 
2107 void CondOpInit::Profile(FoldingSetNodeID &ID) const {
2108   ProfileCondOpInit(ID,
2109       makeArrayRef(getTrailingObjects<Init *>(), NumConds),
2110       makeArrayRef(getTrailingObjects<Init *>() + NumConds, NumConds),
2111       ValType);
2112 }
2113 
2114 CondOpInit *CondOpInit::get(ArrayRef<Init *> CondRange,
2115                             ArrayRef<Init *> ValRange, RecTy *Ty) {
2116   assert(CondRange.size() == ValRange.size() &&
2117          "Number of conditions and values must match!");
2118 
2119   FoldingSetNodeID ID;
2120   ProfileCondOpInit(ID, CondRange, ValRange, Ty);
2121 
2122   detail::RecordKeeperImpl &RK = Ty->getRecordKeeper().getImpl();
2123   void *IP = nullptr;
2124   if (CondOpInit *I = RK.TheCondOpInitPool.FindNodeOrInsertPos(ID, IP))
2125     return I;
2126 
2127   void *Mem = RK.Allocator.Allocate(
2128       totalSizeToAlloc<Init *>(2 * CondRange.size()), alignof(BitsInit));
2129   CondOpInit *I = new(Mem) CondOpInit(CondRange.size(), Ty);
2130 
2131   std::uninitialized_copy(CondRange.begin(), CondRange.end(),
2132                           I->getTrailingObjects<Init *>());
2133   std::uninitialized_copy(ValRange.begin(), ValRange.end(),
2134                           I->getTrailingObjects<Init *>()+CondRange.size());
2135   RK.TheCondOpInitPool.InsertNode(I, IP);
2136   return I;
2137 }
2138 
2139 Init *CondOpInit::resolveReferences(Resolver &R) const {
2140   SmallVector<Init*, 4> NewConds;
2141   bool Changed = false;
2142   for (const Init *Case : getConds()) {
2143     Init *NewCase = Case->resolveReferences(R);
2144     NewConds.push_back(NewCase);
2145     Changed |= NewCase != Case;
2146   }
2147 
2148   SmallVector<Init*, 4> NewVals;
2149   for (const Init *Val : getVals()) {
2150     Init *NewVal = Val->resolveReferences(R);
2151     NewVals.push_back(NewVal);
2152     Changed |= NewVal != Val;
2153   }
2154 
2155   if (Changed)
2156     return (CondOpInit::get(NewConds, NewVals,
2157             getValType()))->Fold(R.getCurrentRecord());
2158 
2159   return const_cast<CondOpInit *>(this);
2160 }
2161 
2162 Init *CondOpInit::Fold(Record *CurRec) const {
2163   RecordKeeper &RK = getRecordKeeper();
2164   for ( unsigned i = 0; i < NumConds; ++i) {
2165     Init *Cond = getCond(i);
2166     Init *Val = getVal(i);
2167 
2168     if (IntInit *CondI = dyn_cast_or_null<IntInit>(
2169             Cond->convertInitializerTo(IntRecTy::get(RK)))) {
2170       if (CondI->getValue())
2171         return Val->convertInitializerTo(getValType());
2172     } else {
2173       return const_cast<CondOpInit *>(this);
2174     }
2175   }
2176 
2177   PrintFatalError(CurRec->getLoc(),
2178                   CurRec->getName() +
2179                   " does not have any true condition in:" +
2180                   this->getAsString());
2181   return nullptr;
2182 }
2183 
2184 bool CondOpInit::isConcrete() const {
2185   for (const Init *Case : getConds())
2186     if (!Case->isConcrete())
2187       return false;
2188 
2189   for (const Init *Val : getVals())
2190     if (!Val->isConcrete())
2191       return false;
2192 
2193   return true;
2194 }
2195 
2196 bool CondOpInit::isComplete() const {
2197   for (const Init *Case : getConds())
2198     if (!Case->isComplete())
2199       return false;
2200 
2201   for (const Init *Val : getVals())
2202     if (!Val->isConcrete())
2203       return false;
2204 
2205   return true;
2206 }
2207 
2208 std::string CondOpInit::getAsString() const {
2209   std::string Result = "!cond(";
2210   for (unsigned i = 0; i < getNumConds(); i++) {
2211     Result += getCond(i)->getAsString() + ": ";
2212     Result += getVal(i)->getAsString();
2213     if (i != getNumConds()-1)
2214       Result += ", ";
2215   }
2216   return Result + ")";
2217 }
2218 
2219 Init *CondOpInit::getBit(unsigned Bit) const {
2220   return VarBitInit::get(const_cast<CondOpInit *>(this), Bit);
2221 }
2222 
2223 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, StringInit *VN,
2224                            ArrayRef<Init *> ArgRange,
2225                            ArrayRef<StringInit *> NameRange) {
2226   ID.AddPointer(V);
2227   ID.AddPointer(VN);
2228 
2229   ArrayRef<Init *>::iterator Arg = ArgRange.begin();
2230   ArrayRef<StringInit *>::iterator Name = NameRange.begin();
2231   while (Arg != ArgRange.end()) {
2232     assert(Name != NameRange.end() && "Arg name underflow!");
2233     ID.AddPointer(*Arg++);
2234     ID.AddPointer(*Name++);
2235   }
2236   assert(Name == NameRange.end() && "Arg name overflow!");
2237 }
2238 
2239 DagInit *DagInit::get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
2240                       ArrayRef<StringInit *> NameRange) {
2241   FoldingSetNodeID ID;
2242   ProfileDagInit(ID, V, VN, ArgRange, NameRange);
2243 
2244   detail::RecordKeeperImpl &RK = V->getRecordKeeper().getImpl();
2245   void *IP = nullptr;
2246   if (DagInit *I = RK.TheDagInitPool.FindNodeOrInsertPos(ID, IP))
2247     return I;
2248 
2249   void *Mem = RK.Allocator.Allocate(
2250       totalSizeToAlloc<Init *, StringInit *>(ArgRange.size(), NameRange.size()),
2251       alignof(BitsInit));
2252   DagInit *I = new (Mem) DagInit(V, VN, ArgRange.size(), NameRange.size());
2253   std::uninitialized_copy(ArgRange.begin(), ArgRange.end(),
2254                           I->getTrailingObjects<Init *>());
2255   std::uninitialized_copy(NameRange.begin(), NameRange.end(),
2256                           I->getTrailingObjects<StringInit *>());
2257   RK.TheDagInitPool.InsertNode(I, IP);
2258   return I;
2259 }
2260 
2261 DagInit *
2262 DagInit::get(Init *V, StringInit *VN,
2263              ArrayRef<std::pair<Init*, StringInit*>> args) {
2264   SmallVector<Init *, 8> Args;
2265   SmallVector<StringInit *, 8> Names;
2266 
2267   for (const auto &Arg : args) {
2268     Args.push_back(Arg.first);
2269     Names.push_back(Arg.second);
2270   }
2271 
2272   return DagInit::get(V, VN, Args, Names);
2273 }
2274 
2275 void DagInit::Profile(FoldingSetNodeID &ID) const {
2276   ProfileDagInit(ID, Val, ValName, makeArrayRef(getTrailingObjects<Init *>(), NumArgs), makeArrayRef(getTrailingObjects<StringInit *>(), NumArgNames));
2277 }
2278 
2279 Record *DagInit::getOperatorAsDef(ArrayRef<SMLoc> Loc) const {
2280   if (DefInit *DefI = dyn_cast<DefInit>(Val))
2281     return DefI->getDef();
2282   PrintFatalError(Loc, "Expected record as operator");
2283   return nullptr;
2284 }
2285 
2286 Init *DagInit::resolveReferences(Resolver &R) const {
2287   SmallVector<Init*, 8> NewArgs;
2288   NewArgs.reserve(arg_size());
2289   bool ArgsChanged = false;
2290   for (const Init *Arg : getArgs()) {
2291     Init *NewArg = Arg->resolveReferences(R);
2292     NewArgs.push_back(NewArg);
2293     ArgsChanged |= NewArg != Arg;
2294   }
2295 
2296   Init *Op = Val->resolveReferences(R);
2297   if (Op != Val || ArgsChanged)
2298     return DagInit::get(Op, ValName, NewArgs, getArgNames());
2299 
2300   return const_cast<DagInit *>(this);
2301 }
2302 
2303 bool DagInit::isConcrete() const {
2304   if (!Val->isConcrete())
2305     return false;
2306   for (const Init *Elt : getArgs()) {
2307     if (!Elt->isConcrete())
2308       return false;
2309   }
2310   return true;
2311 }
2312 
2313 std::string DagInit::getAsString() const {
2314   std::string Result = "(" + Val->getAsString();
2315   if (ValName)
2316     Result += ":" + ValName->getAsUnquotedString();
2317   if (!arg_empty()) {
2318     Result += " " + getArg(0)->getAsString();
2319     if (getArgName(0)) Result += ":$" + getArgName(0)->getAsUnquotedString();
2320     for (unsigned i = 1, e = getNumArgs(); i != e; ++i) {
2321       Result += ", " + getArg(i)->getAsString();
2322       if (getArgName(i)) Result += ":$" + getArgName(i)->getAsUnquotedString();
2323     }
2324   }
2325   return Result + ")";
2326 }
2327 
2328 //===----------------------------------------------------------------------===//
2329 //    Other implementations
2330 //===----------------------------------------------------------------------===//
2331 
2332 RecordVal::RecordVal(Init *N, RecTy *T, FieldKind K)
2333     : Name(N), TyAndKind(T, K) {
2334   setValue(UnsetInit::get(N->getRecordKeeper()));
2335   assert(Value && "Cannot create unset value for current type!");
2336 }
2337 
2338 // This constructor accepts the same arguments as the above, but also
2339 // a source location.
2340 RecordVal::RecordVal(Init *N, SMLoc Loc, RecTy *T, FieldKind K)
2341     : Name(N), Loc(Loc), TyAndKind(T, K) {
2342   setValue(UnsetInit::get(N->getRecordKeeper()));
2343   assert(Value && "Cannot create unset value for current type!");
2344 }
2345 
2346 StringRef RecordVal::getName() const {
2347   return cast<StringInit>(getNameInit())->getValue();
2348 }
2349 
2350 std::string RecordVal::getPrintType() const {
2351   if (getType() == StringRecTy::get(getRecordKeeper())) {
2352     if (auto *StrInit = dyn_cast<StringInit>(Value)) {
2353       if (StrInit->hasCodeFormat())
2354         return "code";
2355       else
2356         return "string";
2357     } else {
2358       return "string";
2359     }
2360   } else {
2361     return TyAndKind.getPointer()->getAsString();
2362   }
2363 }
2364 
2365 bool RecordVal::setValue(Init *V) {
2366   if (V) {
2367     Value = V->getCastTo(getType());
2368     if (Value) {
2369       assert(!isa<TypedInit>(Value) ||
2370              cast<TypedInit>(Value)->getType()->typeIsA(getType()));
2371       if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {
2372         if (!isa<BitsInit>(Value)) {
2373           SmallVector<Init *, 64> Bits;
2374           Bits.reserve(BTy->getNumBits());
2375           for (unsigned I = 0, E = BTy->getNumBits(); I < E; ++I)
2376             Bits.push_back(Value->getBit(I));
2377           Value = BitsInit::get(V->getRecordKeeper(), Bits);
2378         }
2379       }
2380     }
2381     return Value == nullptr;
2382   }
2383   Value = nullptr;
2384   return false;
2385 }
2386 
2387 // This version of setValue takes a source location and resets the
2388 // location in the RecordVal.
2389 bool RecordVal::setValue(Init *V, SMLoc NewLoc) {
2390   Loc = NewLoc;
2391   if (V) {
2392     Value = V->getCastTo(getType());
2393     if (Value) {
2394       assert(!isa<TypedInit>(Value) ||
2395              cast<TypedInit>(Value)->getType()->typeIsA(getType()));
2396       if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {
2397         if (!isa<BitsInit>(Value)) {
2398           SmallVector<Init *, 64> Bits;
2399           Bits.reserve(BTy->getNumBits());
2400           for (unsigned I = 0, E = BTy->getNumBits(); I < E; ++I)
2401             Bits.push_back(Value->getBit(I));
2402           Value = BitsInit::get(getRecordKeeper(), Bits);
2403         }
2404       }
2405     }
2406     return Value == nullptr;
2407   }
2408   Value = nullptr;
2409   return false;
2410 }
2411 
2412 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2413 #include "llvm/TableGen/Record.h"
2414 LLVM_DUMP_METHOD void RecordVal::dump() const { errs() << *this; }
2415 #endif
2416 
2417 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
2418   if (isNonconcreteOK()) OS << "field ";
2419   OS << getPrintType() << " " << getNameInitAsString();
2420 
2421   if (getValue())
2422     OS << " = " << *getValue();
2423 
2424   if (PrintSem) OS << ";\n";
2425 }
2426 
2427 void Record::updateClassLoc(SMLoc Loc) {
2428   assert(Locs.size() == 1);
2429   ForwardDeclarationLocs.push_back(Locs.front());
2430 
2431   Locs.clear();
2432   Locs.push_back(Loc);
2433 }
2434 
2435 void Record::checkName() {
2436   // Ensure the record name has string type.
2437   const TypedInit *TypedName = cast<const TypedInit>(Name);
2438   if (!isa<StringRecTy>(TypedName->getType()))
2439     PrintFatalError(getLoc(), Twine("Record name '") + Name->getAsString() +
2440                                   "' is not a string!");
2441 }
2442 
2443 RecordRecTy *Record::getType() {
2444   SmallVector<Record *, 4> DirectSCs;
2445   getDirectSuperClasses(DirectSCs);
2446   return RecordRecTy::get(TrackedRecords, DirectSCs);
2447 }
2448 
2449 DefInit *Record::getDefInit() {
2450   if (!CorrespondingDefInit) {
2451     CorrespondingDefInit =
2452         new (TrackedRecords.getImpl().Allocator) DefInit(this);
2453   }
2454   return CorrespondingDefInit;
2455 }
2456 
2457 unsigned Record::getNewUID(RecordKeeper &RK) {
2458   return RK.getImpl().LastRecordID++;
2459 }
2460 
2461 void Record::setName(Init *NewName) {
2462   Name = NewName;
2463   checkName();
2464   // DO NOT resolve record values to the name at this point because
2465   // there might be default values for arguments of this def.  Those
2466   // arguments might not have been resolved yet so we don't want to
2467   // prematurely assume values for those arguments were not passed to
2468   // this def.
2469   //
2470   // Nonetheless, it may be that some of this Record's values
2471   // reference the record name.  Indeed, the reason for having the
2472   // record name be an Init is to provide this flexibility.  The extra
2473   // resolve steps after completely instantiating defs takes care of
2474   // this.  See TGParser::ParseDef and TGParser::ParseDefm.
2475 }
2476 
2477 // NOTE for the next two functions:
2478 // Superclasses are in post-order, so the final one is a direct
2479 // superclass. All of its transitive superclases immediately precede it,
2480 // so we can step through the direct superclasses in reverse order.
2481 
2482 bool Record::hasDirectSuperClass(const Record *Superclass) const {
2483   ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();
2484 
2485   for (int I = SCs.size() - 1; I >= 0; --I) {
2486     const Record *SC = SCs[I].first;
2487     if (SC == Superclass)
2488       return true;
2489     I -= SC->getSuperClasses().size();
2490   }
2491 
2492   return false;
2493 }
2494 
2495 void Record::getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const {
2496   ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();
2497 
2498   while (!SCs.empty()) {
2499     Record *SC = SCs.back().first;
2500     SCs = SCs.drop_back(1 + SC->getSuperClasses().size());
2501     Classes.push_back(SC);
2502   }
2503 }
2504 
2505 void Record::resolveReferences(Resolver &R, const RecordVal *SkipVal) {
2506   Init *OldName = getNameInit();
2507   Init *NewName = Name->resolveReferences(R);
2508   if (NewName != OldName) {
2509     // Re-register with RecordKeeper.
2510     setName(NewName);
2511   }
2512 
2513   // Resolve the field values.
2514   for (RecordVal &Value : Values) {
2515     if (SkipVal == &Value) // Skip resolve the same field as the given one
2516       continue;
2517     if (Init *V = Value.getValue()) {
2518       Init *VR = V->resolveReferences(R);
2519       if (Value.setValue(VR)) {
2520         std::string Type;
2521         if (TypedInit *VRT = dyn_cast<TypedInit>(VR))
2522           Type =
2523               (Twine("of type '") + VRT->getType()->getAsString() + "' ").str();
2524         PrintFatalError(
2525             getLoc(),
2526             Twine("Invalid value ") + Type + "found when setting field '" +
2527                 Value.getNameInitAsString() + "' of type '" +
2528                 Value.getType()->getAsString() +
2529                 "' after resolving references: " + VR->getAsUnquotedString() +
2530                 "\n");
2531       }
2532     }
2533   }
2534 
2535   // Resolve the assertion expressions.
2536   for (auto &Assertion : Assertions) {
2537     Init *Value = Assertion.Condition->resolveReferences(R);
2538     Assertion.Condition = Value;
2539     Value = Assertion.Message->resolveReferences(R);
2540     Assertion.Message = Value;
2541   }
2542 }
2543 
2544 void Record::resolveReferences(Init *NewName) {
2545   RecordResolver R(*this);
2546   R.setName(NewName);
2547   R.setFinal(true);
2548   resolveReferences(R);
2549 }
2550 
2551 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2552 LLVM_DUMP_METHOD void Record::dump() const { errs() << *this; }
2553 #endif
2554 
2555 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
2556   OS << R.getNameInitAsString();
2557 
2558   ArrayRef<Init *> TArgs = R.getTemplateArgs();
2559   if (!TArgs.empty()) {
2560     OS << "<";
2561     bool NeedComma = false;
2562     for (const Init *TA : TArgs) {
2563       if (NeedComma) OS << ", ";
2564       NeedComma = true;
2565       const RecordVal *RV = R.getValue(TA);
2566       assert(RV && "Template argument record not found??");
2567       RV->print(OS, false);
2568     }
2569     OS << ">";
2570   }
2571 
2572   OS << " {";
2573   ArrayRef<std::pair<Record *, SMRange>> SC = R.getSuperClasses();
2574   if (!SC.empty()) {
2575     OS << "\t//";
2576     for (const auto &SuperPair : SC)
2577       OS << " " << SuperPair.first->getNameInitAsString();
2578   }
2579   OS << "\n";
2580 
2581   for (const RecordVal &Val : R.getValues())
2582     if (Val.isNonconcreteOK() && !R.isTemplateArg(Val.getNameInit()))
2583       OS << Val;
2584   for (const RecordVal &Val : R.getValues())
2585     if (!Val.isNonconcreteOK() && !R.isTemplateArg(Val.getNameInit()))
2586       OS << Val;
2587 
2588   return OS << "}\n";
2589 }
2590 
2591 SMLoc Record::getFieldLoc(StringRef FieldName) const {
2592   const RecordVal *R = getValue(FieldName);
2593   if (!R)
2594     PrintFatalError(getLoc(), "Record `" + getName() +
2595       "' does not have a field named `" + FieldName + "'!\n");
2596   return R->getLoc();
2597 }
2598 
2599 Init *Record::getValueInit(StringRef FieldName) const {
2600   const RecordVal *R = getValue(FieldName);
2601   if (!R || !R->getValue())
2602     PrintFatalError(getLoc(), "Record `" + getName() +
2603       "' does not have a field named `" + FieldName + "'!\n");
2604   return R->getValue();
2605 }
2606 
2607 StringRef Record::getValueAsString(StringRef FieldName) const {
2608   llvm::Optional<StringRef> S = getValueAsOptionalString(FieldName);
2609   if (!S)
2610     PrintFatalError(getLoc(), "Record `" + getName() +
2611       "' does not have a field named `" + FieldName + "'!\n");
2612   return S.value();
2613 }
2614 
2615 llvm::Optional<StringRef>
2616 Record::getValueAsOptionalString(StringRef FieldName) const {
2617   const RecordVal *R = getValue(FieldName);
2618   if (!R || !R->getValue())
2619     return llvm::Optional<StringRef>();
2620   if (isa<UnsetInit>(R->getValue()))
2621     return llvm::Optional<StringRef>();
2622 
2623   if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
2624     return SI->getValue();
2625 
2626   PrintFatalError(getLoc(),
2627                   "Record `" + getName() + "', ` field `" + FieldName +
2628                       "' exists but does not have a string initializer!");
2629 }
2630 
2631 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
2632   const RecordVal *R = getValue(FieldName);
2633   if (!R || !R->getValue())
2634     PrintFatalError(getLoc(), "Record `" + getName() +
2635       "' does not have a field named `" + FieldName + "'!\n");
2636 
2637   if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
2638     return BI;
2639   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +
2640                                 "' exists but does not have a bits value");
2641 }
2642 
2643 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
2644   const RecordVal *R = getValue(FieldName);
2645   if (!R || !R->getValue())
2646     PrintFatalError(getLoc(), "Record `" + getName() +
2647       "' does not have a field named `" + FieldName + "'!\n");
2648 
2649   if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
2650     return LI;
2651   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +
2652                                 "' exists but does not have a list value");
2653 }
2654 
2655 std::vector<Record*>
2656 Record::getValueAsListOfDefs(StringRef FieldName) const {
2657   ListInit *List = getValueAsListInit(FieldName);
2658   std::vector<Record*> Defs;
2659   for (Init *I : List->getValues()) {
2660     if (DefInit *DI = dyn_cast<DefInit>(I))
2661       Defs.push_back(DI->getDef());
2662     else
2663       PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2664         FieldName + "' list is not entirely DefInit!");
2665   }
2666   return Defs;
2667 }
2668 
2669 int64_t Record::getValueAsInt(StringRef FieldName) const {
2670   const RecordVal *R = getValue(FieldName);
2671   if (!R || !R->getValue())
2672     PrintFatalError(getLoc(), "Record `" + getName() +
2673       "' does not have a field named `" + FieldName + "'!\n");
2674 
2675   if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
2676     return II->getValue();
2677   PrintFatalError(getLoc(), Twine("Record `") + getName() + "', field `" +
2678                                 FieldName +
2679                                 "' exists but does not have an int value: " +
2680                                 R->getValue()->getAsString());
2681 }
2682 
2683 std::vector<int64_t>
2684 Record::getValueAsListOfInts(StringRef FieldName) const {
2685   ListInit *List = getValueAsListInit(FieldName);
2686   std::vector<int64_t> Ints;
2687   for (Init *I : List->getValues()) {
2688     if (IntInit *II = dyn_cast<IntInit>(I))
2689       Ints.push_back(II->getValue());
2690     else
2691       PrintFatalError(getLoc(),
2692                       Twine("Record `") + getName() + "', field `" + FieldName +
2693                           "' exists but does not have a list of ints value: " +
2694                           I->getAsString());
2695   }
2696   return Ints;
2697 }
2698 
2699 std::vector<StringRef>
2700 Record::getValueAsListOfStrings(StringRef FieldName) const {
2701   ListInit *List = getValueAsListInit(FieldName);
2702   std::vector<StringRef> Strings;
2703   for (Init *I : List->getValues()) {
2704     if (StringInit *SI = dyn_cast<StringInit>(I))
2705       Strings.push_back(SI->getValue());
2706     else
2707       PrintFatalError(getLoc(),
2708                       Twine("Record `") + getName() + "', field `" + FieldName +
2709                           "' exists but does not have a list of strings value: " +
2710                           I->getAsString());
2711   }
2712   return Strings;
2713 }
2714 
2715 Record *Record::getValueAsDef(StringRef FieldName) const {
2716   const RecordVal *R = getValue(FieldName);
2717   if (!R || !R->getValue())
2718     PrintFatalError(getLoc(), "Record `" + getName() +
2719       "' does not have a field named `" + FieldName + "'!\n");
2720 
2721   if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
2722     return DI->getDef();
2723   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2724     FieldName + "' does not have a def initializer!");
2725 }
2726 
2727 Record *Record::getValueAsOptionalDef(StringRef FieldName) const {
2728   const RecordVal *R = getValue(FieldName);
2729   if (!R || !R->getValue())
2730     PrintFatalError(getLoc(), "Record `" + getName() +
2731       "' does not have a field named `" + FieldName + "'!\n");
2732 
2733   if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
2734     return DI->getDef();
2735   if (isa<UnsetInit>(R->getValue()))
2736     return nullptr;
2737   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2738     FieldName + "' does not have either a def initializer or '?'!");
2739 }
2740 
2741 
2742 bool Record::getValueAsBit(StringRef FieldName) const {
2743   const RecordVal *R = getValue(FieldName);
2744   if (!R || !R->getValue())
2745     PrintFatalError(getLoc(), "Record `" + getName() +
2746       "' does not have a field named `" + FieldName + "'!\n");
2747 
2748   if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
2749     return BI->getValue();
2750   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2751     FieldName + "' does not have a bit initializer!");
2752 }
2753 
2754 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
2755   const RecordVal *R = getValue(FieldName);
2756   if (!R || !R->getValue())
2757     PrintFatalError(getLoc(), "Record `" + getName() +
2758       "' does not have a field named `" + FieldName.str() + "'!\n");
2759 
2760   if (isa<UnsetInit>(R->getValue())) {
2761     Unset = true;
2762     return false;
2763   }
2764   Unset = false;
2765   if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
2766     return BI->getValue();
2767   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2768     FieldName + "' does not have a bit initializer!");
2769 }
2770 
2771 DagInit *Record::getValueAsDag(StringRef FieldName) const {
2772   const RecordVal *R = getValue(FieldName);
2773   if (!R || !R->getValue())
2774     PrintFatalError(getLoc(), "Record `" + getName() +
2775       "' does not have a field named `" + FieldName + "'!\n");
2776 
2777   if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
2778     return DI;
2779   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2780     FieldName + "' does not have a dag initializer!");
2781 }
2782 
2783 // Check all record assertions: For each one, resolve the condition
2784 // and message, then call CheckAssert().
2785 // Note: The condition and message are probably already resolved,
2786 //       but resolving again allows calls before records are resolved.
2787 void Record::checkRecordAssertions() {
2788   RecordResolver R(*this);
2789   R.setFinal(true);
2790 
2791   for (const auto &Assertion : getAssertions()) {
2792     Init *Condition = Assertion.Condition->resolveReferences(R);
2793     Init *Message = Assertion.Message->resolveReferences(R);
2794     CheckAssert(Assertion.Loc, Condition, Message);
2795   }
2796 }
2797 
2798 // Report a warning if the record has unused template arguments.
2799 void Record::checkUnusedTemplateArgs() {
2800   for (const Init *TA : getTemplateArgs()) {
2801     const RecordVal *Arg = getValue(TA);
2802     if (!Arg->isUsed())
2803       PrintWarning(Arg->getLoc(),
2804                    "unused template argument: " + Twine(Arg->getName()));
2805   }
2806 }
2807 
2808 RecordKeeper::RecordKeeper()
2809     : Impl(std::make_unique<detail::RecordKeeperImpl>(*this)) {}
2810 RecordKeeper::~RecordKeeper() = default;
2811 
2812 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2813 LLVM_DUMP_METHOD void RecordKeeper::dump() const { errs() << *this; }
2814 #endif
2815 
2816 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
2817   OS << "------------- Classes -----------------\n";
2818   for (const auto &C : RK.getClasses())
2819     OS << "class " << *C.second;
2820 
2821   OS << "------------- Defs -----------------\n";
2822   for (const auto &D : RK.getDefs())
2823     OS << "def " << *D.second;
2824   return OS;
2825 }
2826 
2827 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
2828 /// an identifier.
2829 Init *RecordKeeper::getNewAnonymousName() {
2830   return AnonymousNameInit::get(*this, getImpl().AnonCounter++);
2831 }
2832 
2833 // These functions implement the phase timing facility. Starting a timer
2834 // when one is already running stops the running one.
2835 
2836 void RecordKeeper::startTimer(StringRef Name) {
2837   if (TimingGroup) {
2838     if (LastTimer && LastTimer->isRunning()) {
2839       LastTimer->stopTimer();
2840       if (BackendTimer) {
2841         LastTimer->clear();
2842         BackendTimer = false;
2843       }
2844     }
2845 
2846     LastTimer = new Timer("", Name, *TimingGroup);
2847     LastTimer->startTimer();
2848   }
2849 }
2850 
2851 void RecordKeeper::stopTimer() {
2852   if (TimingGroup) {
2853     assert(LastTimer && "No phase timer was started");
2854     LastTimer->stopTimer();
2855   }
2856 }
2857 
2858 void RecordKeeper::startBackendTimer(StringRef Name) {
2859   if (TimingGroup) {
2860     startTimer(Name);
2861     BackendTimer = true;
2862   }
2863 }
2864 
2865 void RecordKeeper::stopBackendTimer() {
2866   if (TimingGroup) {
2867     if (BackendTimer) {
2868       stopTimer();
2869       BackendTimer = false;
2870     }
2871   }
2872 }
2873 
2874 std::vector<Record *>
2875 RecordKeeper::getAllDerivedDefinitions(StringRef ClassName) const {
2876   // We cache the record vectors for single classes. Many backends request
2877   // the same vectors multiple times.
2878   auto Pair = ClassRecordsMap.try_emplace(ClassName);
2879   if (Pair.second)
2880     Pair.first->second = getAllDerivedDefinitions(makeArrayRef(ClassName));
2881 
2882   return Pair.first->second;
2883 }
2884 
2885 std::vector<Record *> RecordKeeper::getAllDerivedDefinitions(
2886     ArrayRef<StringRef> ClassNames) const {
2887   SmallVector<Record *, 2> ClassRecs;
2888   std::vector<Record *> Defs;
2889 
2890   assert(ClassNames.size() > 0 && "At least one class must be passed.");
2891   for (const auto &ClassName : ClassNames) {
2892     Record *Class = getClass(ClassName);
2893     if (!Class)
2894       PrintFatalError("The class '" + ClassName + "' is not defined\n");
2895     ClassRecs.push_back(Class);
2896   }
2897 
2898   for (const auto &OneDef : getDefs()) {
2899     if (all_of(ClassRecs, [&OneDef](const Record *Class) {
2900                             return OneDef.second->isSubClassOf(Class);
2901                           }))
2902       Defs.push_back(OneDef.second.get());
2903   }
2904 
2905   return Defs;
2906 }
2907 
2908 std::vector<Record *>
2909 RecordKeeper::getAllDerivedDefinitionsIfDefined(StringRef ClassName) const {
2910   return getClass(ClassName) ? getAllDerivedDefinitions(ClassName)
2911                              : std::vector<Record *>();
2912 }
2913 
2914 Init *MapResolver::resolve(Init *VarName) {
2915   auto It = Map.find(VarName);
2916   if (It == Map.end())
2917     return nullptr;
2918 
2919   Init *I = It->second.V;
2920 
2921   if (!It->second.Resolved && Map.size() > 1) {
2922     // Resolve mutual references among the mapped variables, but prevent
2923     // infinite recursion.
2924     Map.erase(It);
2925     I = I->resolveReferences(*this);
2926     Map[VarName] = {I, true};
2927   }
2928 
2929   return I;
2930 }
2931 
2932 Init *RecordResolver::resolve(Init *VarName) {
2933   Init *Val = Cache.lookup(VarName);
2934   if (Val)
2935     return Val;
2936 
2937   if (llvm::is_contained(Stack, VarName))
2938     return nullptr; // prevent infinite recursion
2939 
2940   if (RecordVal *RV = getCurrentRecord()->getValue(VarName)) {
2941     if (!isa<UnsetInit>(RV->getValue())) {
2942       Val = RV->getValue();
2943       Stack.push_back(VarName);
2944       Val = Val->resolveReferences(*this);
2945       Stack.pop_back();
2946     }
2947   } else if (Name && VarName == getCurrentRecord()->getNameInit()) {
2948     Stack.push_back(VarName);
2949     Val = Name->resolveReferences(*this);
2950     Stack.pop_back();
2951   }
2952 
2953   Cache[VarName] = Val;
2954   return Val;
2955 }
2956 
2957 Init *TrackUnresolvedResolver::resolve(Init *VarName) {
2958   Init *I = nullptr;
2959 
2960   if (R) {
2961     I = R->resolve(VarName);
2962     if (I && !FoundUnresolved) {
2963       // Do not recurse into the resolved initializer, as that would change
2964       // the behavior of the resolver we're delegating, but do check to see
2965       // if there are unresolved variables remaining.
2966       TrackUnresolvedResolver Sub;
2967       I->resolveReferences(Sub);
2968       FoundUnresolved |= Sub.FoundUnresolved;
2969     }
2970   }
2971 
2972   if (!I)
2973     FoundUnresolved = true;
2974   return I;
2975 }
2976 
2977 Init *HasReferenceResolver::resolve(Init *VarName)
2978 {
2979   if (VarName == VarNameToTrack)
2980     Found = true;
2981   return nullptr;
2982 }
2983