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