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