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