LLVM 24.0.0git
Record.cpp
Go to the documentation of this file.
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
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/FoldingSet.h"
20#include "llvm/ADT/StringMap.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/Config/llvm-config.h"
28#include "llvm/Support/Regex.h"
29#include "llvm/Support/SMLoc.h"
31#include "llvm/TableGen/Error.h"
33#include <cassert>
34#include <cstdint>
35#include <map>
36#include <memory>
37#include <string>
38#include <utility>
39#include <vector>
40
41using namespace llvm;
42
43#define DEBUG_TYPE "tblgen-records"
44
45//===----------------------------------------------------------------------===//
46// Context
47//===----------------------------------------------------------------------===//
48
49/// This class represents the internal implementation of the RecordKeeper.
50/// It contains all of the contextual static state of the Record classes. It is
51/// kept out-of-line to simplify dependencies, and also make it easier for
52/// internal classes to access the uniquer state of the keeper.
60
62 std::vector<BitsRecTy *> SharedBitsRecTys;
67
72
75 std::map<int64_t, IntInit *> TheIntInitPool;
95
96 unsigned AnonCounter;
97 unsigned LastRecordID;
98
99 void dumpAllocationStats(raw_ostream &OS) const;
100};
101
103 // Dump memory allocation related stats.
104 OS << "TheArgumentInitPool size = " << TheArgumentInitPool.size() << '\n';
105 OS << "TheBitsInitPool size = " << TheBitsInitPool.size() << '\n';
106 OS << "TheIntInitPool size = " << TheIntInitPool.size() << '\n';
107 OS << "StringInitStringPool size = " << StringInitStringPool.size() << '\n';
108 OS << "StringInitCodePool size = " << StringInitCodePool.size() << '\n';
109 OS << "TheListInitPool size = " << TheListInitPool.size() << '\n';
110 OS << "TheUnOpInitPool size = " << TheUnOpInitPool.size() << '\n';
111 OS << "TheBinOpInitPool size = " << TheBinOpInitPool.size() << '\n';
112 OS << "TheTernOpInitPool size = " << TheTernOpInitPool.size() << '\n';
113 OS << "TheFoldOpInitPool size = " << TheFoldOpInitPool.size() << '\n';
114 OS << "TheIsAOpInitPool size = " << TheIsAOpInitPool.size() << '\n';
115 OS << "TheExistsOpInitPool size = " << TheExistsOpInitPool.size() << '\n';
116 OS << "TheCondOpInitPool size = " << TheCondOpInitPool.size() << '\n';
117 OS << "TheDagInitPool size = " << TheDagInitPool.size() << '\n';
118 OS << "RecordTypePool size = " << RecordTypePool.size() << '\n';
119 OS << "TheVarInitPool size = " << TheVarInitPool.size() << '\n';
120 OS << "TheVarBitInitPool size = " << TheVarBitInitPool.size() << '\n';
121 OS << "TheVarDefInitPool size = " << TheVarDefInitPool.size() << '\n';
122 OS << "TheFieldInitPool size = " << TheFieldInitPool.size() << '\n';
123 OS << "Total allocator memory = " << Allocator.getTotalMemory() << "\n\n";
124
125 OS << "Number of records instantiated = " << LastRecordID << '\n';
126 OS << "Number of anonymous records = " << AnonCounter << '\n';
127}
128
129//===----------------------------------------------------------------------===//
130// Type implementations
131//===----------------------------------------------------------------------===//
132
133#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
135#endif
136
138 if (!ListTy)
139 ListTy = new (RK.getImpl().Allocator) ListRecTy(this);
140 return ListTy;
141}
142
143bool RecTy::typeIsConvertibleTo(const RecTy *RHS) const {
144 assert(RHS && "NULL pointer");
145 return Kind == RHS->getRecTyKind();
146}
147
148bool RecTy::typeIsA(const RecTy *RHS) const { return this == RHS; }
149
150const BitRecTy *BitRecTy::get(RecordKeeper &RK) {
151 return &RK.getImpl().SharedBitRecTy;
152}
153
155 if (RecTy::typeIsConvertibleTo(RHS) || RHS->getRecTyKind() == IntRecTyKind)
156 return true;
157 if (const auto *BitsTy = dyn_cast<BitsRecTy>(RHS))
158 return BitsTy->getNumBits() == 1;
159 return false;
160}
161
162const BitsRecTy *BitsRecTy::get(RecordKeeper &RK, unsigned Sz) {
163 detail::RecordKeeperImpl &RKImpl = RK.getImpl();
164 if (Sz >= RKImpl.SharedBitsRecTys.size())
165 RKImpl.SharedBitsRecTys.resize(Sz + 1);
166 BitsRecTy *&Ty = RKImpl.SharedBitsRecTys[Sz];
167 if (!Ty)
168 Ty = new (RKImpl.Allocator) BitsRecTy(RK, Sz);
169 return Ty;
170}
171
172std::string BitsRecTy::getAsString() const {
173 return "bits<" + utostr(Size) + ">";
174}
175
176bool BitsRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
177 if (RecTy::typeIsConvertibleTo(RHS)) //argument and the sender are same type
178 return cast<BitsRecTy>(RHS)->Size == Size;
179 RecTyKind kind = RHS->getRecTyKind();
180 return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
181}
182
183const IntRecTy *IntRecTy::get(RecordKeeper &RK) {
184 return &RK.getImpl().SharedIntRecTy;
185}
186
187bool IntRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
188 RecTyKind kind = RHS->getRecTyKind();
189 return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
190}
191
192const StringRecTy *StringRecTy::get(RecordKeeper &RK) {
193 return &RK.getImpl().SharedStringRecTy;
194}
195
196std::string StringRecTy::getAsString() const {
197 return "string";
198}
199
201 RecTyKind Kind = RHS->getRecTyKind();
202 return Kind == StringRecTyKind;
203}
204
205std::string ListRecTy::getAsString() const {
206 return "list<" + ElementTy->getAsString() + ">";
207}
208
209bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
210 if (const auto *ListTy = dyn_cast<ListRecTy>(RHS))
211 return ElementTy->typeIsConvertibleTo(ListTy->getElementType());
212 return false;
213}
214
215bool ListRecTy::typeIsA(const RecTy *RHS) const {
216 if (const auto *RHSl = dyn_cast<ListRecTy>(RHS))
217 return getElementType()->typeIsA(RHSl->getElementType());
218 return false;
219}
220
221const DagRecTy *DagRecTy::get(RecordKeeper &RK) {
222 return &RK.getImpl().SharedDagRecTy;
223}
224
225std::string DagRecTy::getAsString() const {
226 return "dag";
227}
228
230 ArrayRef<const Record *> Classes) {
231 ID.AddInteger(Classes.size());
232 for (const Record *R : Classes)
233 ID.AddPointer(R);
234}
235
236RecordRecTy::RecordRecTy(RecordKeeper &RK, ArrayRef<const Record *> Classes)
237 : RecTy(RecordRecTyKind, RK), NumClasses(Classes.size()) {
238 llvm::uninitialized_copy(Classes, getTrailingObjects());
239}
240
241const RecordRecTy *RecordRecTy::get(RecordKeeper &RK,
242 ArrayRef<const Record *> UnsortedClasses) {
243 detail::RecordKeeperImpl &RKImpl = RK.getImpl();
244 if (UnsortedClasses.empty())
245 return &RKImpl.AnyRecord;
246
247 FoldingSet<RecordRecTy> &ThePool = RKImpl.RecordTypePool;
248
249 SmallVector<const Record *, 4> Classes(UnsortedClasses);
250 llvm::sort(Classes, [](const Record *LHS, const Record *RHS) {
251 return LHS->getNameInitAsString() < RHS->getNameInitAsString();
252 });
253
255 ProfileRecordRecTy(ID, Classes);
256
258 if (RecordRecTy *Ty = ThePool.lookup(ID, Token))
259 return Ty;
260
261#ifndef NDEBUG
262 // Check for redundancy.
263 for (unsigned i = 0; i < Classes.size(); ++i) {
264 for (unsigned j = 0; j < Classes.size(); ++j) {
265 assert(i == j || !Classes[i]->isSubClassOf(Classes[j]));
266 }
267 assert(&Classes[0]->getRecords() == &Classes[i]->getRecords());
268 }
269#endif
270
271 void *Mem = RKImpl.Allocator.Allocate(
272 totalSizeToAlloc<const Record *>(Classes.size()), alignof(RecordRecTy));
273 RecordRecTy *Ty = new (Mem) RecordRecTy(RK, Classes);
274 ThePool.insert(Ty, Token);
275 return Ty;
276}
277
278const RecordRecTy *RecordRecTy::get(const Record *Class) {
279 assert(Class && "unexpected null class");
280 return get(Class->getRecords(), {Class});
281}
282
286
287std::string RecordRecTy::getAsString() const {
288 if (NumClasses == 1)
289 return getClasses()[0]->getNameInitAsString();
290
291 std::string Str = "{";
292 ListSeparator LS;
293 for (const Record *R : getClasses()) {
294 Str += LS;
295 Str += R->getNameInitAsString();
296 }
297 Str += "}";
298 return Str;
299}
300
301bool RecordRecTy::isSubClassOf(const Record *Class) const {
302 return llvm::any_of(getClasses(), [Class](const Record *MySuperClass) {
303 return MySuperClass == Class || MySuperClass->isSubClassOf(Class);
304 });
305}
306
308 if (this == RHS)
309 return true;
310
311 const auto *RTy = dyn_cast<RecordRecTy>(RHS);
312 if (!RTy)
313 return false;
314
315 return llvm::all_of(RTy->getClasses(), [this](const Record *TargetClass) {
316 return isSubClassOf(TargetClass);
317 });
318}
319
320bool RecordRecTy::typeIsA(const RecTy *RHS) const {
321 return typeIsConvertibleTo(RHS);
322}
323
325 const RecordRecTy *T2) {
326 SmallVector<const Record *, 4> CommonSuperClasses;
327 SmallVector<const Record *, 4> Stack(T1->getClasses());
328
329 while (!Stack.empty()) {
330 const Record *R = Stack.pop_back_val();
331
332 if (T2->isSubClassOf(R))
333 CommonSuperClasses.push_back(R);
334 else
335 llvm::append_range(Stack, make_first_range(R->getDirectSuperClasses()));
336 }
337
338 return RecordRecTy::get(T1->getRecordKeeper(), CommonSuperClasses);
339}
340
341const RecTy *llvm::resolveTypes(const RecTy *T1, const RecTy *T2) {
342 if (T1 == T2)
343 return T1;
344
345 if (const auto *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
346 if (const auto *RecTy2 = dyn_cast<RecordRecTy>(T2))
347 return resolveRecordTypes(RecTy1, RecTy2);
348 }
349
350 assert(T1 != nullptr && "Invalid record type");
351 if (T1->typeIsConvertibleTo(T2))
352 return T2;
353
354 assert(T2 != nullptr && "Invalid record type");
355 if (T2->typeIsConvertibleTo(T1))
356 return T1;
357
358 if (const auto *ListTy1 = dyn_cast<ListRecTy>(T1)) {
359 if (const auto *ListTy2 = dyn_cast<ListRecTy>(T2)) {
360 const RecTy *NewType =
361 resolveTypes(ListTy1->getElementType(), ListTy2->getElementType());
362 if (NewType)
363 return NewType->getListTy();
364 }
365 }
366
367 return nullptr;
368}
369
370//===----------------------------------------------------------------------===//
371// Initializer implementations
372//===----------------------------------------------------------------------===//
373
374void Init::anchor() {}
375
376#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
377LLVM_DUMP_METHOD void Init::dump() const { return print(errs()); }
378#endif
379
381 if (auto *TyInit = dyn_cast<TypedInit>(this))
382 return TyInit->getType()->getRecordKeeper();
383 if (auto *ArgInit = dyn_cast<ArgumentInit>(this))
384 return ArgInit->getRecordKeeper();
385 return cast<UnsetInit>(this)->getRecordKeeper();
386}
387
389 return &RK.getImpl().TheUnsetInit;
390}
391
392const Init *UnsetInit::getCastTo(const RecTy *Ty) const { return this; }
393
395 return this;
396}
397
399 ArgAuxType Aux) {
400 auto I = Aux.index();
401 ID.AddInteger(I);
403 ID.AddInteger(std::get<ArgumentInit::Positional>(Aux));
404 if (I == ArgumentInit::Named)
405 ID.AddPointer(std::get<ArgumentInit::Named>(Aux));
406 ID.AddPointer(Value);
407}
408
410 ProfileArgumentInit(ID, Value, Aux);
411}
412
415 ProfileArgumentInit(ID, Value, Aux);
416
417 RecordKeeper &RK = Value->getRecordKeeper();
418 detail::RecordKeeperImpl &RKImpl = RK.getImpl();
420 if (const ArgumentInit *I = RKImpl.TheArgumentInitPool.lookup(ID, Token))
421 return I;
422
423 ArgumentInit *I = new (RKImpl.Allocator) ArgumentInit(Value, Aux);
424 RKImpl.TheArgumentInitPool.insert(I, Token);
425 return I;
426}
427
429 const Init *NewValue = Value->resolveReferences(R);
430 if (NewValue != Value)
431 return cloneWithValue(NewValue);
432
433 return this;
434}
435
436BitInit *BitInit::get(RecordKeeper &RK, bool V) {
437 return V ? &RK.getImpl().TrueBitInit : &RK.getImpl().FalseBitInit;
438}
439
440const Init *BitInit::convertInitializerTo(const RecTy *Ty) const {
441 if (isa<BitRecTy>(Ty))
442 return this;
443
444 if (isa<IntRecTy>(Ty))
446
447 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
448 // Can only convert single bit.
449 if (BRT->getNumBits() == 1)
450 return BitsInit::get(getRecordKeeper(), this);
451 }
452
453 return nullptr;
454}
455
458 ID.AddInteger(Range.size());
459
460 for (const Init *I : Range)
461 ID.AddPointer(I);
462}
463
464BitsInit::BitsInit(RecordKeeper &RK, ArrayRef<const Init *> Bits)
465 : TypedInit(IK_BitsInit, BitsRecTy::get(RK, Bits.size())),
466 NumBits(Bits.size()) {
467 llvm::uninitialized_copy(Bits, getTrailingObjects());
468}
469
472 ProfileBitsInit(ID, Bits);
473
474 detail::RecordKeeperImpl &RKImpl = RK.getImpl();
476 if (BitsInit *I = RKImpl.TheBitsInitPool.lookup(ID, Token))
477 return I;
478
479 void *Mem = RKImpl.Allocator.Allocate(
480 totalSizeToAlloc<const Init *>(Bits.size()), alignof(BitsInit));
481 BitsInit *I = new (Mem) BitsInit(RK, Bits);
482 RKImpl.TheBitsInitPool.insert(I, Token);
483 return I;
484}
485
489
491 if (isa<BitRecTy>(Ty)) {
492 if (getNumBits() != 1) return nullptr; // Only accept if just one bit!
493 return getBit(0);
494 }
495
496 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
497 // If the number of bits is right, return it. Otherwise we need to expand
498 // or truncate.
499 if (getNumBits() != BRT->getNumBits()) return nullptr;
500 return this;
501 }
502
503 if (isa<IntRecTy>(Ty)) {
504 std::optional<int64_t> Result = convertInitializerToInt();
505 if (Result)
506 return IntInit::get(getRecordKeeper(), *Result);
507 }
508
509 return nullptr;
510}
511
512std::optional<int64_t> BitsInit::convertInitializerToInt() const {
513 int64_t Result = 0;
514 for (auto [Idx, InitV] : enumerate(getBits()))
515 if (auto *Bit = dyn_cast<BitInit>(InitV))
516 Result |= static_cast<int64_t>(Bit->getValue()) << Idx;
517 else
518 return std::nullopt;
519 return Result;
520}
521
523 uint64_t Result = 0;
524 for (auto [Idx, InitV] : enumerate(getBits()))
525 if (auto *Bit = dyn_cast<BitInit>(InitV))
526 Result |= static_cast<int64_t>(Bit->getValue()) << Idx;
527 return Result;
528}
529
530const Init *
532 SmallVector<const Init *, 16> NewBits(Bits.size());
533
534 for (auto [Bit, NewBit] : zip_equal(Bits, NewBits)) {
535 if (Bit >= getNumBits())
536 return nullptr;
537 NewBit = getBit(Bit);
538 }
539 return BitsInit::get(getRecordKeeper(), NewBits);
540}
541
543 return all_of(getBits(), [](const Init *Bit) { return Bit->isComplete(); });
544}
546 return all_of(getBits(), [](const Init *Bit) { return !Bit->isComplete(); });
547}
549 return all_of(getBits(), [](const Init *Bit) { return Bit->isConcrete(); });
550}
551
552std::string BitsInit::getAsString() const {
553 std::string Result = "{ ";
554 ListSeparator LS;
555 for (const Init *Bit : reverse(getBits())) {
556 Result += LS;
557 if (Bit)
558 Result += Bit->getAsString();
559 else
560 Result += "*";
561 }
562 return Result + " }";
563}
564
565// resolveReferences - If there are any field references that refer to fields
566// that have been filled in, we can propagate the values now.
568 bool Changed = false;
570
571 const Init *CachedBitVarRef = nullptr;
572 const Init *CachedBitVarResolved = nullptr;
573
574 for (auto [CurBit, NewBit] : zip_equal(getBits(), NewBits)) {
575 NewBit = CurBit;
576
577 if (const auto *CurBitVar = dyn_cast<VarBitInit>(CurBit)) {
578 if (CurBitVar->getBitVar() != CachedBitVarRef) {
579 CachedBitVarRef = CurBitVar->getBitVar();
580 CachedBitVarResolved = CachedBitVarRef->resolveReferences(R);
581 }
582 assert(CachedBitVarResolved && "Unresolved bitvar reference");
583 NewBit = CachedBitVarResolved->getBit(CurBitVar->getBitNum());
584 } else {
585 // getBit(0) implicitly converts int and bits<1> values to bit.
586 NewBit = CurBit->resolveReferences(R)->getBit(0);
587 }
588
589 if (isa<UnsetInit>(NewBit) && R.keepUnsetBits())
590 NewBit = CurBit;
591 Changed |= CurBit != NewBit;
592 }
593
594 if (Changed)
595 return BitsInit::get(getRecordKeeper(), NewBits);
596
597 return this;
598}
599
600IntInit *IntInit::get(RecordKeeper &RK, int64_t V) {
601 IntInit *&I = RK.getImpl().TheIntInitPool[V];
602 if (!I)
603 I = new (RK.getImpl().Allocator) IntInit(RK, V);
604 return I;
605}
606
607std::string IntInit::getAsString() const {
608 return itostr(Value);
609}
610
611static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
612 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
613 return (NumBits >= sizeof(Value) * 8) ||
614 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
615}
616
617const Init *IntInit::convertInitializerTo(const RecTy *Ty) const {
618 if (isa<IntRecTy>(Ty))
619 return this;
620
621 if (isa<BitRecTy>(Ty)) {
622 int64_t Val = getValue();
623 if (Val != 0 && Val != 1) return nullptr; // Only accept 0 or 1 for a bit!
624 return BitInit::get(getRecordKeeper(), Val != 0);
625 }
626
627 if (const auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
628 int64_t Value = getValue();
629 // Make sure this bitfield is large enough to hold the integer value.
630 if (!canFitInBitfield(Value, BRT->getNumBits()))
631 return nullptr;
632
633 SmallVector<const Init *, 16> NewBits(BRT->getNumBits());
634 for (unsigned i = 0; i != BRT->getNumBits(); ++i)
635 NewBits[i] =
636 BitInit::get(getRecordKeeper(), Value & ((i < 64) ? (1LL << i) : 0));
637
638 return BitsInit::get(getRecordKeeper(), NewBits);
639 }
640
641 return nullptr;
642}
643
645 SmallVector<const Init *, 16> NewBits(Bits.size());
646
647 for (auto [Bit, NewBit] : zip_equal(Bits, NewBits)) {
648 if (Bit >= 64)
649 return nullptr;
650
651 NewBit = BitInit::get(getRecordKeeper(), Value & (INT64_C(1) << Bit));
652 }
653 return BitsInit::get(getRecordKeeper(), NewBits);
654}
655
656AnonymousNameInit *AnonymousNameInit::get(RecordKeeper &RK, unsigned V) {
657 return new (RK.getImpl().Allocator) AnonymousNameInit(RK, V);
658}
659
663
665 return "anonymous_" + utostr(Value);
666}
667
669 auto *Old = this;
670 auto *New = R.resolve(Old);
671 New = New ? New : Old;
672 if (R.isFinal())
673 if (const auto *Anonymous = dyn_cast<AnonymousNameInit>(New))
674 return Anonymous->getNameInit();
675 return New;
676}
677
678const StringInit *StringInit::get(RecordKeeper &RK, StringRef V,
679 StringFormat Fmt) {
680 detail::RecordKeeperImpl &RKImpl = RK.getImpl();
681 auto &InitMap = Fmt == SF_String ? RKImpl.StringInitStringPool
682 : RKImpl.StringInitCodePool;
683 auto &Entry = *InitMap.try_emplace(V, nullptr).first;
684 if (!Entry.second)
685 Entry.second = new (RKImpl.Allocator) StringInit(RK, Entry.getKey(), Fmt);
686 return Entry.second;
687}
688
690 if (isa<StringRecTy>(Ty))
691 return this;
692
693 return nullptr;
694}
695
696ListInit::ListInit(ArrayRef<const Init *> Elements, const RecTy *EltTy)
697 : TypedInit(IK_ListInit, ListRecTy::get(EltTy)),
698 NumElements(Elements.size()) {
699 llvm::uninitialized_copy(Elements, getTrailingObjects());
700}
701
702const ListInit *ListInit::get(ArrayRef<const Init *> Elements,
703 const RecTy *EltTy) {
706 if (const ListInit *I = RK.TheListInitPool.lookup({Elements, EltTy}, Token))
707 return I;
708
709 assert(Elements.empty() || !isa<TypedInit>(Elements[0]) ||
710 cast<TypedInit>(Elements[0])->getType()->typeIsConvertibleTo(EltTy));
711
712 void *Mem = RK.Allocator.Allocate(
713 totalSizeToAlloc<const Init *>(Elements.size()), alignof(ListInit));
714 ListInit *I = new (Mem) ListInit(Elements, EltTy);
715 RK.TheListInitPool.insert(I, Token);
716 return I;
717}
718
720 if (getType() == Ty)
721 return this;
722
723 if (const auto *LRT = dyn_cast<ListRecTy>(Ty)) {
725 Elements.reserve(size());
726
727 // Verify that all of the elements of the list are subclasses of the
728 // appropriate class!
729 bool Changed = false;
730 const RecTy *ElementType = LRT->getElementType();
731 for (const Init *I : getElements())
732 if (const Init *CI = I->convertInitializerTo(ElementType)) {
733 Elements.push_back(CI);
734 if (CI != I)
735 Changed = true;
736 } else {
737 return nullptr;
738 }
739
740 if (!Changed)
741 return this;
742 return ListInit::get(Elements, ElementType);
743 }
744
745 return nullptr;
746}
747
748const Record *ListInit::getElementAsRecord(unsigned Idx) const {
749 const auto *DI = dyn_cast<DefInit>(getElement(Idx));
750 if (!DI)
751 PrintFatalError("expected record type for the element with index " +
752 Twine(Idx) + " in list " + getAsString());
753 return DI->getDef();
754}
755
758 Resolved.reserve(size());
759 bool Changed = false;
760
761 for (const Init *CurElt : getElements()) {
762 const Init *E = CurElt->resolveReferences(R);
763 Changed |= E != CurElt;
764 Resolved.push_back(E);
765 }
766
767 if (Changed)
768 return ListInit::get(Resolved, getElementType());
769 return this;
770}
771
773 return all_of(*this,
774 [](const Init *Element) { return Element->isComplete(); });
775}
776
778 return all_of(*this,
779 [](const Init *Element) { return Element->isConcrete(); });
780}
781
782std::string ListInit::getAsString() const {
783 std::string Result = "[";
784 ListSeparator LS;
785 for (const Init *Element : *this) {
786 Result += LS;
787 Result += Element->getAsString();
788 }
789 return Result + "]";
790}
791
792const Init *OpInit::getBit(unsigned Bit) const {
793 if (isa<BitRecTy>(getType()))
794 return this;
795 return VarBitInit::get(this, Bit);
796}
797
798const UnOpInit *UnOpInit::get(UnaryOp Opc, const Init *LHS, const RecTy *Type) {
799 detail::RecordKeeperImpl &RK = Type->getRecordKeeper().getImpl();
801 if (const UnOpInit *I = RK.TheUnOpInitPool.lookup({Opc, LHS, Type}, Token))
802 return I;
803
804 UnOpInit *I = new (RK.Allocator) UnOpInit(Opc, LHS, Type);
805 RK.TheUnOpInitPool.insert(I, Token);
806 return I;
807}
808
809const Init *UnOpInit::Fold(const Record *CurRec, bool IsFinal) const {
811 switch (getOpcode()) {
812 case REPR:
813 if (LHS->isConcrete()) {
814 // If it is a Record, print the full content.
815 if (const auto *Def = dyn_cast<DefInit>(LHS)) {
816 std::string S;
817 raw_string_ostream OS(S);
818 OS << *Def->getDef();
819 return StringInit::get(RK, S);
820 } else {
821 // Otherwise, print the value of the variable.
822 //
823 // NOTE: we could recursively !repr the elements of a list,
824 // but that could produce a lot of output when printing a
825 // defset.
826 return StringInit::get(RK, LHS->getAsString());
827 }
828 }
829 break;
830 case TOLOWER:
831 if (const auto *LHSs = dyn_cast<StringInit>(LHS))
832 return StringInit::get(RK, LHSs->getValue().lower());
833 break;
834 case TOUPPER:
835 if (const auto *LHSs = dyn_cast<StringInit>(LHS))
836 return StringInit::get(RK, LHSs->getValue().upper());
837 break;
838 case CAST:
839 if (isa<StringRecTy>(getType())) {
840 if (const auto *LHSs = dyn_cast<StringInit>(LHS))
841 return LHSs;
842
843 if (const auto *LHSd = dyn_cast<DefInit>(LHS))
844 return StringInit::get(RK, LHSd->getAsString());
845
846 if (const auto *LHSi = dyn_cast_or_null<IntInit>(
847 LHS->convertInitializerTo(IntRecTy::get(RK))))
848 return StringInit::get(RK, LHSi->getAsString());
849
850 } else if (isa<RecordRecTy>(getType())) {
851 if (const auto *Name = dyn_cast<StringInit>(LHS)) {
852 const Record *D = RK.getDef(Name->getValue());
853 if (!D && CurRec) {
854 // Self-references are allowed, but their resolution is delayed until
855 // the final resolve to ensure that we get the correct type for them.
856 auto *Anonymous = dyn_cast<AnonymousNameInit>(CurRec->getNameInit());
857 if (Name == CurRec->getNameInit() ||
858 (Anonymous && Name == Anonymous->getNameInit())) {
859 if (!IsFinal)
860 break;
861 D = CurRec;
862 }
863 }
864
865 auto PrintFatalErrorHelper = [CurRec](const Twine &T) {
866 if (CurRec)
867 PrintFatalError(CurRec->getLoc(), T);
868 else
870 };
871
872 if (!D) {
873 if (IsFinal) {
874 PrintFatalErrorHelper(Twine("Undefined reference to record: '") +
875 Name->getValue() + "'\n");
876 }
877 break;
878 }
879
880 DefInit *DI = D->getDefInit();
881 if (!DI->getType()->typeIsA(getType())) {
882 PrintFatalErrorHelper(Twine("Expected type '") +
883 getType()->getAsString() + "', got '" +
884 DI->getType()->getAsString() + "' in: " +
885 getAsString() + "\n");
886 }
887 return DI;
888 }
889 }
890
891 if (const Init *NewInit = LHS->convertInitializerTo(getType()))
892 return NewInit;
893 break;
894
895 case INITIALIZED:
896 if (isa<UnsetInit>(LHS))
897 return IntInit::get(RK, 0);
898 if (LHS->isConcrete())
899 return IntInit::get(RK, 1);
900 break;
901
902 case NOT:
903 if (const auto *LHSi = dyn_cast_or_null<IntInit>(
904 LHS->convertInitializerTo(IntRecTy::get(RK))))
905 return IntInit::get(RK, LHSi->getValue() ? 0 : 1);
906 break;
907
908 case HEAD:
909 if (const auto *LHSl = dyn_cast<ListInit>(LHS)) {
910 assert(!LHSl->empty() && "Empty list in head");
911 return LHSl->getElement(0);
912 }
913 break;
914
915 case TAIL:
916 if (const auto *LHSl = dyn_cast<ListInit>(LHS)) {
917 assert(!LHSl->empty() && "Empty list in tail");
918 // Note the slice(1). We can't just pass the result of getElements()
919 // directly.
920 return ListInit::get(LHSl->getElements().slice(1),
921 LHSl->getElementType());
922 }
923 break;
924
925 case SIZE:
926 if (const auto *LHSl = dyn_cast<ListInit>(LHS))
927 return IntInit::get(RK, LHSl->size());
928 if (const auto *LHSd = dyn_cast<DagInit>(LHS))
929 return IntInit::get(RK, LHSd->arg_size());
930 if (const auto *LHSs = dyn_cast<StringInit>(LHS))
931 return IntInit::get(RK, LHSs->getValue().size());
932 break;
933
934 case EMPTY:
935 if (const auto *LHSl = dyn_cast<ListInit>(LHS))
936 return IntInit::get(RK, LHSl->empty());
937 if (const auto *LHSd = dyn_cast<DagInit>(LHS))
938 return IntInit::get(RK, LHSd->arg_empty());
939 if (const auto *LHSs = dyn_cast<StringInit>(LHS))
940 return IntInit::get(RK, LHSs->getValue().empty());
941 break;
942
943 case GETDAGOP:
944 if (const auto *Dag = dyn_cast<DagInit>(LHS)) {
945 // TI is not necessarily a def due to the late resolution in multiclasses,
946 // but has to be a TypedInit.
947 auto *TI = cast<TypedInit>(Dag->getOperator());
948 if (!TI->getType()->typeIsA(getType())) {
949 PrintFatalError(CurRec->getLoc(),
950 Twine("Expected type '") + getType()->getAsString() +
951 "', got '" + TI->getType()->getAsString() +
952 "' in: " + getAsString() + "\n");
953 } else {
954 return Dag->getOperator();
955 }
956 }
957 break;
958
959 case GETDAGOPNAME:
960 if (const auto *Dag = dyn_cast<DagInit>(LHS)) {
961 return Dag->getName();
962 }
963 break;
964
965 case LOG2:
966 if (const auto *LHSi = dyn_cast_or_null<IntInit>(
967 LHS->convertInitializerTo(IntRecTy::get(RK)))) {
968 int64_t LHSv = LHSi->getValue();
969 if (LHSv <= 0) {
970 PrintFatalError(CurRec->getLoc(),
971 "Illegal operation: logtwo is undefined "
972 "on arguments less than or equal to 0");
973 } else {
974 uint64_t Log = Log2_64(LHSv);
975 assert(Log <= INT64_MAX &&
976 "Log of an int64_t must be smaller than INT64_MAX");
977 return IntInit::get(RK, static_cast<int64_t>(Log));
978 }
979 }
980 break;
981
982 case LISTFLATTEN:
983 if (const auto *LHSList = dyn_cast<ListInit>(LHS)) {
984 const auto *InnerListTy = dyn_cast<ListRecTy>(LHSList->getElementType());
985 // list of non-lists, !listflatten() is a NOP.
986 if (!InnerListTy)
987 return LHS;
988
989 auto Flatten =
990 [](const ListInit *List) -> std::optional<std::vector<const Init *>> {
991 std::vector<const Init *> Flattened;
992 // Concatenate elements of all the inner lists.
993 for (const Init *InnerInit : List->getElements()) {
994 const auto *InnerList = dyn_cast<ListInit>(InnerInit);
995 if (!InnerList)
996 return std::nullopt;
997 llvm::append_range(Flattened, InnerList->getElements());
998 };
999 return Flattened;
1000 };
1001
1002 auto Flattened = Flatten(LHSList);
1003 if (Flattened)
1004 return ListInit::get(*Flattened, InnerListTy->getElementType());
1005 }
1006 break;
1007 }
1008 return this;
1009}
1010
1012 const Init *lhs = LHS->resolveReferences(R);
1013
1014 if (LHS != lhs || (R.isFinal() && getOpcode() == CAST))
1015 return (UnOpInit::get(getOpcode(), lhs, getType()))
1016 ->Fold(R.getCurrentRecord(), R.isFinal());
1017 return this;
1018}
1019
1020std::string UnOpInit::getAsString() const {
1021 std::string Result;
1022 switch (getOpcode()) {
1023 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
1024 case NOT: Result = "!not"; break;
1025 case HEAD: Result = "!head"; break;
1026 case TAIL: Result = "!tail"; break;
1027 case SIZE: Result = "!size"; break;
1028 case EMPTY: Result = "!empty"; break;
1029 case GETDAGOP: Result = "!getdagop"; break;
1030 case GETDAGOPNAME:
1031 Result = "!getdagopname";
1032 break;
1033 case LOG2 : Result = "!logtwo"; break;
1034 case LISTFLATTEN:
1035 Result = "!listflatten";
1036 break;
1037 case REPR:
1038 Result = "!repr";
1039 break;
1040 case TOLOWER:
1041 Result = "!tolower";
1042 break;
1043 case TOUPPER:
1044 Result = "!toupper";
1045 break;
1046 case INITIALIZED:
1047 Result = "!initialized";
1048 break;
1049 }
1050 return Result + "(" + LHS->getAsString() + ")";
1051}
1052
1053const BinOpInit *BinOpInit::get(BinaryOp Opc, const Init *LHS, const Init *RHS,
1054 const RecTy *Type) {
1055 detail::RecordKeeperImpl &RK = LHS->getRecordKeeper().getImpl();
1057 if (const BinOpInit *I =
1058 RK.TheBinOpInitPool.lookup({Opc, LHS, RHS, Type}, Token))
1059 return I;
1060
1061 BinOpInit *I = new (RK.Allocator) BinOpInit(Opc, LHS, RHS, Type);
1062 RK.TheBinOpInitPool.insert(I, Token);
1063 return I;
1064}
1065
1067 const StringInit *I1) {
1069 Concat.append(I1->getValue());
1070 return StringInit::get(
1071 I0->getRecordKeeper(), Concat,
1072 StringInit::determineFormat(I0->getFormat(), I1->getFormat()));
1073}
1074
1075static const StringInit *interleaveStringList(const ListInit *List,
1076 const StringInit *Delim) {
1077 if (List->size() == 0)
1078 return StringInit::get(List->getRecordKeeper(), "");
1079 const auto *Element = dyn_cast<StringInit>(List->getElement(0));
1080 if (!Element)
1081 return nullptr;
1082 SmallString<80> Result(Element->getValue());
1084
1085 for (const Init *Elem : List->getElements().drop_front()) {
1086 Result.append(Delim->getValue());
1087 const auto *Element = dyn_cast<StringInit>(Elem);
1088 if (!Element)
1089 return nullptr;
1090 Result.append(Element->getValue());
1091 Fmt = StringInit::determineFormat(Fmt, Element->getFormat());
1092 }
1093 return StringInit::get(List->getRecordKeeper(), Result, Fmt);
1094}
1095
1096static const StringInit *interleaveIntList(const ListInit *List,
1097 const StringInit *Delim) {
1098 RecordKeeper &RK = List->getRecordKeeper();
1099 if (List->size() == 0)
1100 return StringInit::get(RK, "");
1101 const auto *Element = dyn_cast_or_null<IntInit>(
1102 List->getElement(0)->convertInitializerTo(IntRecTy::get(RK)));
1103 if (!Element)
1104 return nullptr;
1105 SmallString<80> Result(Element->getAsString());
1106
1107 for (const Init *Elem : List->getElements().drop_front()) {
1108 Result.append(Delim->getValue());
1109 const auto *Element = dyn_cast_or_null<IntInit>(
1110 Elem->convertInitializerTo(IntRecTy::get(RK)));
1111 if (!Element)
1112 return nullptr;
1113 Result.append(Element->getAsString());
1114 }
1115 return StringInit::get(RK, Result);
1116}
1117
1118const Init *BinOpInit::getStrConcat(const Init *I0, const Init *I1) {
1119 // Shortcut for the common case of concatenating two strings.
1120 if (const auto *I0s = dyn_cast<StringInit>(I0))
1121 if (const auto *I1s = dyn_cast<StringInit>(I1))
1122 return ConcatStringInits(I0s, I1s);
1123 return BinOpInit::get(BinOpInit::STRCONCAT, I0, I1,
1125}
1126
1128 const ListInit *RHS) {
1130 llvm::append_range(Args, *LHS);
1131 llvm::append_range(Args, *RHS);
1132 return ListInit::get(Args, LHS->getElementType());
1133}
1134
1135const Init *BinOpInit::getListConcat(const TypedInit *LHS, const Init *RHS) {
1136 assert(isa<ListRecTy>(LHS->getType()) && "First arg must be a list");
1137
1138 // Shortcut for the common case of concatenating two lists.
1139 if (const auto *LHSList = dyn_cast<ListInit>(LHS))
1140 if (const auto *RHSList = dyn_cast<ListInit>(RHS))
1141 return ConcatListInits(LHSList, RHSList);
1142 return BinOpInit::get(BinOpInit::LISTCONCAT, LHS, RHS, LHS->getType());
1143}
1144
1145std::optional<bool> BinOpInit::CompareInit(unsigned Opc, const Init *LHS,
1146 const Init *RHS) const {
1147 // First see if we have two bit, bits, or int.
1148 const auto *LHSi = dyn_cast_or_null<IntInit>(
1149 LHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
1150 const auto *RHSi = dyn_cast_or_null<IntInit>(
1151 RHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
1152
1153 if (LHSi && RHSi) {
1154 bool Result;
1155 switch (Opc) {
1156 case EQ:
1157 Result = LHSi->getValue() == RHSi->getValue();
1158 break;
1159 case NE:
1160 Result = LHSi->getValue() != RHSi->getValue();
1161 break;
1162 case LE:
1163 Result = LHSi->getValue() <= RHSi->getValue();
1164 break;
1165 case LT:
1166 Result = LHSi->getValue() < RHSi->getValue();
1167 break;
1168 case GE:
1169 Result = LHSi->getValue() >= RHSi->getValue();
1170 break;
1171 case GT:
1172 Result = LHSi->getValue() > RHSi->getValue();
1173 break;
1174 default:
1175 llvm_unreachable("unhandled comparison");
1176 }
1177 return Result;
1178 }
1179
1180 // Next try strings.
1181 const auto *LHSs = dyn_cast<StringInit>(LHS);
1182 const auto *RHSs = dyn_cast<StringInit>(RHS);
1183
1184 if (LHSs && RHSs) {
1185 bool Result;
1186 switch (Opc) {
1187 case EQ:
1188 Result = LHSs->getValue() == RHSs->getValue();
1189 break;
1190 case NE:
1191 Result = LHSs->getValue() != RHSs->getValue();
1192 break;
1193 case LE:
1194 Result = LHSs->getValue() <= RHSs->getValue();
1195 break;
1196 case LT:
1197 Result = LHSs->getValue() < RHSs->getValue();
1198 break;
1199 case GE:
1200 Result = LHSs->getValue() >= RHSs->getValue();
1201 break;
1202 case GT:
1203 Result = LHSs->getValue() > RHSs->getValue();
1204 break;
1205 default:
1206 llvm_unreachable("unhandled comparison");
1207 }
1208 return Result;
1209 }
1210
1211 // Finally, !eq and !ne can be used with records.
1212 if (Opc == EQ || Opc == NE) {
1213 const auto *LHSd = dyn_cast<DefInit>(LHS);
1214 const auto *RHSd = dyn_cast<DefInit>(RHS);
1215 if (LHSd && RHSd)
1216 return (Opc == EQ) ? LHSd == RHSd : LHSd != RHSd;
1217 }
1218
1219 return std::nullopt;
1220}
1221
1222static std::optional<unsigned>
1223getDagArgNoByKey(const DagInit *Dag, const Init *Key, std::string &Error) {
1224 // Accessor by index
1225 if (const auto *Idx = dyn_cast<IntInit>(Key)) {
1226 int64_t Pos = Idx->getValue();
1227 if (Pos < 0) {
1228 // The index is negative.
1229 Error =
1230 (Twine("index ") + std::to_string(Pos) + Twine(" is negative")).str();
1231 return std::nullopt;
1232 }
1233 if (Pos >= Dag->getNumArgs()) {
1234 // The index is out-of-range.
1235 Error = (Twine("index ") + std::to_string(Pos) +
1236 " is out of range (dag has " +
1237 std::to_string(Dag->getNumArgs()) + " arguments)")
1238 .str();
1239 return std::nullopt;
1240 }
1241 return Pos;
1242 }
1244 // Accessor by name
1245 const auto *Name = dyn_cast<StringInit>(Key);
1246 auto ArgNo = Dag->getArgNo(Name->getValue());
1247 if (!ArgNo) {
1248 // The key is not found.
1249 Error = (Twine("key '") + Name->getValue() + Twine("' is not found")).str();
1250 return std::nullopt;
1251 }
1252 return *ArgNo;
1253}
1254
1255const Init *BinOpInit::Fold(const Record *CurRec) const {
1256 switch (getOpcode()) {
1257 case CONCAT: {
1258 const auto *LHSs = dyn_cast<DagInit>(LHS);
1259 const auto *RHSs = dyn_cast<DagInit>(RHS);
1260 if (LHSs && RHSs) {
1261 const auto *LOp = dyn_cast<DefInit>(LHSs->getOperator());
1262 const auto *ROp = dyn_cast<DefInit>(RHSs->getOperator());
1263 if ((!LOp && !isa<UnsetInit>(LHSs->getOperator())) ||
1264 (!ROp && !isa<UnsetInit>(RHSs->getOperator())))
1265 break;
1266 if (LOp && ROp && LOp->getDef() != ROp->getDef()) {
1267 PrintFatalError(Twine("Concatenated Dag operators do not match: '") +
1268 LHSs->getAsString() + "' vs. '" + RHSs->getAsString() +
1269 "'");
1270 }
1271 const Init *Op = LOp ? LOp : ROp;
1272 if (!Op)
1274
1276 llvm::append_range(Args, LHSs->getArgAndNames());
1277 llvm::append_range(Args, RHSs->getArgAndNames());
1278 // Use the name of the LHS DAG if it's set, otherwise the name of the RHS.
1279 const auto *NameInit = LHSs->getName();
1280 if (!NameInit)
1281 NameInit = RHSs->getName();
1282 return DagInit::get(Op, NameInit, Args);
1283 }
1284 break;
1285 }
1286 case MATCH: {
1287 const auto *StrInit = dyn_cast<StringInit>(LHS);
1288 if (!StrInit)
1289 return this;
1290
1291 const auto *RegexInit = dyn_cast<StringInit>(RHS);
1292 if (!RegexInit)
1293 return this;
1294
1295 StringRef RegexStr = RegexInit->getValue();
1296 llvm::Regex Matcher(RegexStr);
1297 if (!Matcher.isValid())
1298 PrintFatalError(Twine("invalid regex '") + RegexStr + Twine("'"));
1299
1300 return BitInit::get(LHS->getRecordKeeper(),
1301 Matcher.match(StrInit->getValue()));
1302 }
1303 case LISTCONCAT: {
1304 const auto *LHSs = dyn_cast<ListInit>(LHS);
1305 const auto *RHSs = dyn_cast<ListInit>(RHS);
1306 if (LHSs && RHSs) {
1308 llvm::append_range(Args, *LHSs);
1309 llvm::append_range(Args, *RHSs);
1310 return ListInit::get(Args, LHSs->getElementType());
1311 }
1312 break;
1313 }
1314 case LISTSPLAT: {
1315 const auto *Value = dyn_cast<TypedInit>(LHS);
1316 const auto *Count = dyn_cast<IntInit>(RHS);
1317 if (Value && Count) {
1318 if (Count->getValue() < 0)
1319 PrintFatalError(Twine("!listsplat count ") + Count->getAsString() +
1320 " is negative");
1321 SmallVector<const Init *, 8> Args(Count->getValue(), Value);
1322 return ListInit::get(Args, Value->getType());
1323 }
1324 break;
1325 }
1326 case LISTREMOVE: {
1327 const auto *LHSs = dyn_cast<ListInit>(LHS);
1328 const auto *RHSs = dyn_cast<ListInit>(RHS);
1329 if (LHSs && RHSs) {
1331 for (const Init *EltLHS : *LHSs) {
1332 bool Found = false;
1333 for (const Init *EltRHS : *RHSs) {
1334 if (std::optional<bool> Result = CompareInit(EQ, EltLHS, EltRHS)) {
1335 if (*Result) {
1336 Found = true;
1337 break;
1338 }
1339 }
1340 }
1341 if (!Found)
1342 Args.push_back(EltLHS);
1343 }
1344 return ListInit::get(Args, LHSs->getElementType());
1345 }
1346 break;
1347 }
1348 case LISTELEM: {
1349 const auto *TheList = dyn_cast<ListInit>(LHS);
1350 const auto *Idx = dyn_cast<IntInit>(RHS);
1351 if (!TheList || !Idx)
1352 break;
1353 auto i = Idx->getValue();
1354 if (i < 0 || i >= (ssize_t)TheList->size())
1355 break;
1356 return TheList->getElement(i);
1357 }
1358 case LISTSLICE: {
1359 const auto *TheList = dyn_cast<ListInit>(LHS);
1360 const auto *SliceIdxs = dyn_cast<ListInit>(RHS);
1361 if (!TheList || !SliceIdxs)
1362 break;
1364 Args.reserve(SliceIdxs->size());
1365 for (auto *I : *SliceIdxs) {
1366 auto *II = dyn_cast<IntInit>(I);
1367 if (!II)
1368 goto unresolved;
1369 auto i = II->getValue();
1370 if (i < 0 || i >= (ssize_t)TheList->size())
1371 goto unresolved;
1372 Args.push_back(TheList->getElement(i));
1373 }
1374 return ListInit::get(Args, TheList->getElementType());
1375 }
1376 case RANGEC: {
1377 const auto *LHSi = dyn_cast<IntInit>(LHS);
1378 const auto *RHSi = dyn_cast<IntInit>(RHS);
1379 if (!LHSi || !RHSi)
1380 break;
1381
1382 int64_t Start = LHSi->getValue();
1383 int64_t End = RHSi->getValue();
1385 if (getOpcode() == RANGEC) {
1386 // Closed interval
1387 if (Start <= End) {
1388 // Ascending order
1389 Args.reserve(End - Start + 1);
1390 for (auto i = Start; i <= End; ++i)
1391 Args.push_back(IntInit::get(getRecordKeeper(), i));
1392 } else {
1393 // Descending order
1394 Args.reserve(Start - End + 1);
1395 for (auto i = Start; i >= End; --i)
1396 Args.push_back(IntInit::get(getRecordKeeper(), i));
1397 }
1398 } else if (Start < End) {
1399 // Half-open interval (excludes `End`)
1400 Args.reserve(End - Start);
1401 for (auto i = Start; i < End; ++i)
1402 Args.push_back(IntInit::get(getRecordKeeper(), i));
1403 } else {
1404 // Empty set
1405 }
1406 return ListInit::get(Args, LHSi->getType());
1407 }
1408 case STRCONCAT: {
1409 const auto *LHSs = dyn_cast<StringInit>(LHS);
1410 const auto *RHSs = dyn_cast<StringInit>(RHS);
1411 if (LHSs && RHSs)
1412 return ConcatStringInits(LHSs, RHSs);
1413 break;
1414 }
1415 case INTERLEAVE: {
1416 const auto *List = dyn_cast<ListInit>(LHS);
1417 const auto *Delim = dyn_cast<StringInit>(RHS);
1418 if (List && Delim) {
1419 const StringInit *Result;
1420 if (isa<StringRecTy>(List->getElementType()))
1421 Result = interleaveStringList(List, Delim);
1422 else
1423 Result = interleaveIntList(List, Delim);
1424 if (Result)
1425 return Result;
1426 }
1427 break;
1428 }
1429 case EQ:
1430 case NE:
1431 case LE:
1432 case LT:
1433 case GE:
1434 case GT: {
1435 if (std::optional<bool> Result = CompareInit(getOpcode(), LHS, RHS))
1436 return BitInit::get(getRecordKeeper(), *Result);
1437 break;
1438 }
1439 case GETDAGARG: {
1440 const auto *Dag = dyn_cast<DagInit>(LHS);
1441 if (Dag && isa<IntInit, StringInit>(RHS)) {
1442 std::string Error;
1443 auto ArgNo = getDagArgNoByKey(Dag, RHS, Error);
1444 if (!ArgNo)
1445 PrintFatalError(CurRec->getLoc(), "!getdagarg " + Error);
1446
1447 assert(*ArgNo < Dag->getNumArgs());
1448
1449 const Init *Arg = Dag->getArg(*ArgNo);
1450 if (const auto *TI = dyn_cast<TypedInit>(Arg))
1451 if (!TI->getType()->typeIsConvertibleTo(getType()))
1452 return UnsetInit::get(Dag->getRecordKeeper());
1453 return Arg;
1454 }
1455 break;
1456 }
1457 case GETDAGNAME: {
1458 const auto *Dag = dyn_cast<DagInit>(LHS);
1459 const auto *Idx = dyn_cast<IntInit>(RHS);
1460 if (Dag && Idx) {
1461 int64_t Pos = Idx->getValue();
1462 if (Pos < 0 || Pos >= Dag->getNumArgs()) {
1463 // The index is out-of-range.
1464 PrintError(CurRec->getLoc(),
1465 Twine("!getdagname index is out of range 0...") +
1466 std::to_string(Dag->getNumArgs() - 1) + ": " +
1467 std::to_string(Pos));
1468 }
1469 const Init *ArgName = Dag->getArgName(Pos);
1470 if (!ArgName)
1472 return ArgName;
1473 }
1474 break;
1475 }
1476 case SETDAGOP: {
1477 const auto *Dag = dyn_cast<DagInit>(LHS);
1478 const auto *Op = dyn_cast<DefInit>(RHS);
1479 if (Dag && Op)
1480 return DagInit::get(Op, Dag->getArgs(), Dag->getArgNames());
1481 break;
1482 }
1483 case SETDAGOPNAME: {
1484 const auto *Dag = dyn_cast<DagInit>(LHS);
1485 const auto *Op = dyn_cast<StringInit>(RHS);
1486 if (Dag && Op)
1487 return DagInit::get(Dag->getOperator(), Op, Dag->getArgs(),
1488 Dag->getArgNames());
1489 break;
1490 }
1491 case ADD:
1492 case SUB:
1493 case MUL:
1494 case DIV:
1495 case AND:
1496 case OR:
1497 case XOR:
1498 case SHL:
1499 case SRA:
1500 case SRL: {
1501 const auto *LHSi = dyn_cast_or_null<IntInit>(
1502 LHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
1503 const auto *RHSi = dyn_cast_or_null<IntInit>(
1504 RHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
1505 if (LHSi && RHSi) {
1506 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
1507 int64_t Result;
1508 switch (getOpcode()) {
1509 default: llvm_unreachable("Bad opcode!");
1510 case ADD: Result = LHSv + RHSv; break;
1511 case SUB: Result = LHSv - RHSv; break;
1512 case MUL: Result = LHSv * RHSv; break;
1513 case DIV:
1514 if (RHSv == 0)
1515 PrintFatalError(CurRec->getLoc(),
1516 "Illegal operation: division by zero");
1517 else if (LHSv == INT64_MIN && RHSv == -1)
1518 PrintFatalError(CurRec->getLoc(),
1519 "Illegal operation: INT64_MIN / -1");
1520 else
1521 Result = LHSv / RHSv;
1522 break;
1523 case AND: Result = LHSv & RHSv; break;
1524 case OR: Result = LHSv | RHSv; break;
1525 case XOR: Result = LHSv ^ RHSv; break;
1526 case SHL:
1527 if (RHSv < 0 || RHSv >= 64)
1528 PrintFatalError(CurRec->getLoc(),
1529 "Illegal operation: out of bounds shift");
1530 Result = (uint64_t)LHSv << (uint64_t)RHSv;
1531 break;
1532 case SRA:
1533 if (RHSv < 0 || RHSv >= 64)
1534 PrintFatalError(CurRec->getLoc(),
1535 "Illegal operation: out of bounds shift");
1536 Result = LHSv >> (uint64_t)RHSv;
1537 break;
1538 case SRL:
1539 if (RHSv < 0 || RHSv >= 64)
1540 PrintFatalError(CurRec->getLoc(),
1541 "Illegal operation: out of bounds shift");
1542 Result = (uint64_t)LHSv >> (uint64_t)RHSv;
1543 break;
1544 }
1545 return IntInit::get(getRecordKeeper(), Result);
1546 }
1547 break;
1548 }
1549 }
1550unresolved:
1551 return this;
1552}
1553
1555 const Init *NewLHS = LHS->resolveReferences(R);
1556
1557 unsigned Opc = getOpcode();
1558 if (Opc == AND || Opc == OR) {
1559 // Short-circuit. Regardless whether this is a logical or bitwise
1560 // AND/OR.
1561 // Ideally we could also short-circuit `!or(true, ...)`, but it's
1562 // difficult to do it right without knowing if rest of the operands
1563 // are all `bit` or not. Therefore, we're only implementing a relatively
1564 // limited version of short-circuit against all ones (`true` is casted
1565 // to 1 rather than all ones before we evaluate `!or`).
1566 if (const auto *LHSi = dyn_cast_or_null<IntInit>(
1568 if ((Opc == AND && !LHSi->getValue()) ||
1569 (Opc == OR && LHSi->getValue() == -1))
1570 return LHSi;
1571 }
1572 }
1573
1574 const Init *NewRHS = RHS->resolveReferences(R);
1575
1576 if (LHS != NewLHS || RHS != NewRHS)
1577 return (BinOpInit::get(getOpcode(), NewLHS, NewRHS, getType()))
1578 ->Fold(R.getCurrentRecord());
1579 return this;
1580}
1581
1582std::string BinOpInit::getAsString() const {
1583 std::string Result;
1584 switch (getOpcode()) {
1585 case LISTELEM:
1586 case LISTSLICE:
1587 return LHS->getAsString() + "[" + RHS->getAsString() + "]";
1588 case RANGEC:
1589 return LHS->getAsString() + "..." + RHS->getAsString();
1590 case CONCAT: Result = "!con"; break;
1591 case MATCH:
1592 Result = "!match";
1593 break;
1594 case ADD: Result = "!add"; break;
1595 case SUB: Result = "!sub"; break;
1596 case MUL: Result = "!mul"; break;
1597 case DIV: Result = "!div"; break;
1598 case AND: Result = "!and"; break;
1599 case OR: Result = "!or"; break;
1600 case XOR: Result = "!xor"; break;
1601 case SHL: Result = "!shl"; break;
1602 case SRA: Result = "!sra"; break;
1603 case SRL: Result = "!srl"; break;
1604 case EQ: Result = "!eq"; break;
1605 case NE: Result = "!ne"; break;
1606 case LE: Result = "!le"; break;
1607 case LT: Result = "!lt"; break;
1608 case GE: Result = "!ge"; break;
1609 case GT: Result = "!gt"; break;
1610 case LISTCONCAT: Result = "!listconcat"; break;
1611 case LISTSPLAT: Result = "!listsplat"; break;
1612 case LISTREMOVE:
1613 Result = "!listremove";
1614 break;
1615 case STRCONCAT: Result = "!strconcat"; break;
1616 case INTERLEAVE: Result = "!interleave"; break;
1617 case SETDAGOP: Result = "!setdagop"; break;
1618 case SETDAGOPNAME:
1619 Result = "!setdagopname";
1620 break;
1621 case GETDAGARG:
1622 Result = "!getdagarg<" + getType()->getAsString() + ">";
1623 break;
1624 case GETDAGNAME:
1625 Result = "!getdagname";
1626 break;
1627 }
1628 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
1629}
1630
1631const TernOpInit *TernOpInit::get(TernaryOp Opc, const Init *LHS,
1632 const Init *MHS, const Init *RHS,
1633 const RecTy *Type) {
1634 detail::RecordKeeperImpl &RK = LHS->getRecordKeeper().getImpl();
1636 if (TernOpInit *I =
1637 RK.TheTernOpInitPool.lookup({Opc, LHS, MHS, RHS, Type}, Token))
1638 return I;
1639
1640 TernOpInit *I = new (RK.Allocator) TernOpInit(Opc, LHS, MHS, RHS, Type);
1641 RK.TheTernOpInitPool.insert(I, Token);
1642 return I;
1643}
1644
1645static const Init *ItemApply(const Init *LHS, const Init *MHSe, const Init *RHS,
1646 const Record *CurRec) {
1647 MapResolver R(CurRec);
1648 R.set(LHS, MHSe);
1649 return RHS->resolveReferences(R);
1650}
1651
1652static const Init *ForeachDagApply(const Init *LHS, const DagInit *MHSd,
1653 const Init *RHS, const Record *CurRec) {
1654 bool Change = false;
1655 const Init *Val = ItemApply(LHS, MHSd->getOperator(), RHS, CurRec);
1656 if (Val != MHSd->getOperator())
1657 Change = true;
1658
1660 for (auto [Arg, ArgName] : MHSd->getArgAndNames()) {
1661 const Init *NewArg;
1662
1663 if (const auto *Argd = dyn_cast<DagInit>(Arg))
1664 NewArg = ForeachDagApply(LHS, Argd, RHS, CurRec);
1665 else
1666 NewArg = ItemApply(LHS, Arg, RHS, CurRec);
1667
1668 NewArgs.emplace_back(NewArg, ArgName);
1669 if (Arg != NewArg)
1670 Change = true;
1671 }
1672
1673 if (Change)
1674 return DagInit::get(Val, MHSd->getName(), NewArgs);
1675 return MHSd;
1676}
1677
1678// Applies RHS to all elements of MHS, using LHS as a temp variable.
1679static const Init *ForeachHelper(const Init *LHS, const Init *MHS,
1680 const Init *RHS, const RecTy *Type,
1681 const Record *CurRec) {
1682 if (const auto *MHSd = dyn_cast<DagInit>(MHS))
1683 return ForeachDagApply(LHS, MHSd, RHS, CurRec);
1684
1685 if (const auto *MHSl = dyn_cast<ListInit>(MHS)) {
1686 SmallVector<const Init *, 8> NewList(MHSl->begin(), MHSl->end());
1687
1688 for (const Init *&Item : NewList) {
1689 const Init *NewItem = ItemApply(LHS, Item, RHS, CurRec);
1690 if (NewItem != Item)
1691 Item = NewItem;
1692 }
1693 return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
1694 }
1695
1696 return nullptr;
1697}
1698
1699// Evaluates RHS for all elements of MHS, using LHS as a temp variable.
1700// Creates a new list with the elements that evaluated to true.
1701static const Init *FilterHelper(const Init *LHS, const Init *MHS,
1702 const Init *RHS, const RecTy *Type,
1703 const Record *CurRec) {
1704 if (const auto *MHSl = dyn_cast<ListInit>(MHS)) {
1706
1707 for (const Init *Item : MHSl->getElements()) {
1708 const Init *Include = ItemApply(LHS, Item, RHS, CurRec);
1709 if (!Include)
1710 return nullptr;
1711 if (const auto *IncludeInt =
1712 dyn_cast_or_null<IntInit>(Include->convertInitializerTo(
1713 IntRecTy::get(LHS->getRecordKeeper())))) {
1714 if (IncludeInt->getValue())
1715 NewList.push_back(Item);
1716 } else {
1717 return nullptr;
1718 }
1719 }
1720 return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
1721 }
1722
1723 return nullptr;
1724}
1725
1726static const Init *SortHelper(const Init *LHS, const Init *MHS, const Init *RHS,
1727 const RecTy *Type, const Record *CurRec) {
1728 const auto *MHSl = dyn_cast<ListInit>(MHS);
1729 if (!MHSl)
1730 return nullptr;
1731
1732 RecordKeeper &RK = LHS->getRecordKeeper();
1733 using KV = std::pair<const Init *, const Init *>;
1734 SmallVector<KV, 8> KeyedList;
1735
1736 for (const Init *Item : MHSl->getElements()) {
1737 const Init *Key = ItemApply(LHS, Item, RHS, CurRec);
1738 if (!Key)
1739 return nullptr;
1740 KeyedList.emplace_back(Key, Item);
1741 }
1742
1743 if (KeyedList.empty())
1744 return ListInit::get({}, cast<ListRecTy>(Type)->getElementType());
1745
1746 // Determine key type from the first element; all keys must agree.
1747 bool UseInt =
1748 dyn_cast_or_null<IntInit>(KeyedList[0].first->convertInitializerTo(
1749 IntRecTy::get(RK))) != nullptr;
1750 for (auto &[Key, Item] : KeyedList) {
1751 if (UseInt) {
1753 Key->convertInitializerTo(IntRecTy::get(RK))))
1754 return nullptr;
1755 } else {
1756 if (!isa<StringInit>(Key))
1757 return nullptr;
1758 }
1759 }
1760
1761 llvm::stable_sort(KeyedList, [&RK, UseInt](const KV &A, const KV &B) {
1762 if (UseInt)
1763 return cast<IntInit>(A.first->convertInitializerTo(IntRecTy::get(RK)))
1764 ->getValue() <
1765 cast<IntInit>(B.first->convertInitializerTo(IntRecTy::get(RK)))
1766 ->getValue();
1767 return cast<StringInit>(A.first)->getValue() <
1768 cast<StringInit>(B.first)->getValue();
1769 });
1770
1772 for (auto &[Key, Item] : KeyedList)
1773 Result.push_back(Item);
1774 return ListInit::get(Result, cast<ListRecTy>(Type)->getElementType());
1775}
1776
1777const Init *TernOpInit::Fold(const Record *CurRec) const {
1779 switch (getOpcode()) {
1780 case SUBST: {
1781 const auto *LHSd = dyn_cast<DefInit>(LHS);
1782 const auto *LHSv = dyn_cast<VarInit>(LHS);
1783 const auto *LHSs = dyn_cast<StringInit>(LHS);
1784
1785 const auto *MHSd = dyn_cast<DefInit>(MHS);
1786 const auto *MHSv = dyn_cast<VarInit>(MHS);
1787 const auto *MHSs = dyn_cast<StringInit>(MHS);
1788
1789 const auto *RHSd = dyn_cast<DefInit>(RHS);
1790 const auto *RHSv = dyn_cast<VarInit>(RHS);
1791 const auto *RHSs = dyn_cast<StringInit>(RHS);
1792
1793 if (LHSd && MHSd && RHSd) {
1794 const Record *Val = RHSd->getDef();
1795 if (LHSd->getAsString() == RHSd->getAsString())
1796 Val = MHSd->getDef();
1797 return Val->getDefInit();
1798 }
1799 if (LHSv && MHSv && RHSv) {
1800 std::string Val = RHSv->getName().str();
1801 if (LHSv->getAsString() == RHSv->getAsString())
1802 Val = MHSv->getName().str();
1803 return VarInit::get(Val, getType());
1804 }
1805 if (LHSs && MHSs && RHSs) {
1806 std::string Val = RHSs->getValue().str();
1807
1808 std::string::size_type Idx = 0;
1809 while (true) {
1810 std::string::size_type Found = Val.find(LHSs->getValue(), Idx);
1811 if (Found == std::string::npos)
1812 break;
1813 Val.replace(Found, LHSs->getValue().size(), MHSs->getValue().str());
1814 Idx = Found + MHSs->getValue().size();
1815 }
1816
1817 return StringInit::get(RK, Val);
1818 }
1819 break;
1820 }
1821
1822 case FOREACH: {
1823 if (const Init *Result = ForeachHelper(LHS, MHS, RHS, getType(), CurRec))
1824 return Result;
1825 break;
1826 }
1827
1828 case FILTER: {
1829 if (const Init *Result = FilterHelper(LHS, MHS, RHS, getType(), CurRec))
1830 return Result;
1831 break;
1832 }
1833
1834 case SORT: {
1835 if (const Init *Result = SortHelper(LHS, MHS, RHS, getType(), CurRec))
1836 return Result;
1837 break;
1838 }
1839
1840 case IF: {
1841 if (const auto *LHSi = dyn_cast_or_null<IntInit>(
1842 LHS->convertInitializerTo(IntRecTy::get(RK)))) {
1843 if (LHSi->getValue())
1844 return MHS;
1845 return RHS;
1846 }
1847 break;
1848 }
1849
1850 case DAG: {
1851 const auto *MHSl = dyn_cast<ListInit>(MHS);
1852 const auto *RHSl = dyn_cast<ListInit>(RHS);
1853 bool MHSok = MHSl || isa<UnsetInit>(MHS);
1854 bool RHSok = RHSl || isa<UnsetInit>(RHS);
1855
1856 if (isa<UnsetInit>(MHS) && isa<UnsetInit>(RHS))
1857 break; // Typically prevented by the parser, but might happen with template args
1858
1859 if (MHSok && RHSok && (!MHSl || !RHSl || MHSl->size() == RHSl->size())) {
1861 unsigned Size = MHSl ? MHSl->size() : RHSl->size();
1862 for (unsigned i = 0; i != Size; ++i) {
1863 const Init *Node = MHSl ? MHSl->getElement(i) : UnsetInit::get(RK);
1864 const Init *Name = RHSl ? RHSl->getElement(i) : UnsetInit::get(RK);
1865 if (!isa<StringInit>(Name) && !isa<UnsetInit>(Name))
1866 return this;
1867 Children.emplace_back(Node, dyn_cast<StringInit>(Name));
1868 }
1869 return DagInit::get(LHS, Children);
1870 }
1871 break;
1872 }
1873
1874 case RANGE: {
1875 const auto *LHSi = dyn_cast<IntInit>(LHS);
1876 const auto *MHSi = dyn_cast<IntInit>(MHS);
1877 const auto *RHSi = dyn_cast<IntInit>(RHS);
1878 if (!LHSi || !MHSi || !RHSi)
1879 break;
1880
1881 auto Start = LHSi->getValue();
1882 auto End = MHSi->getValue();
1883 auto Step = RHSi->getValue();
1884 if (Step == 0)
1885 PrintError(CurRec->getLoc(), "Step of !range can't be 0");
1886
1888 if (Start < End && Step > 0) {
1889 Args.reserve((End - Start) / Step);
1890 for (auto I = Start; I < End; I += Step)
1891 Args.push_back(IntInit::get(getRecordKeeper(), I));
1892 } else if (Start > End && Step < 0) {
1893 Args.reserve((Start - End) / -Step);
1894 for (auto I = Start; I > End; I += Step)
1895 Args.push_back(IntInit::get(getRecordKeeper(), I));
1896 } else {
1897 // Empty set
1898 }
1899 return ListInit::get(Args, LHSi->getType());
1900 }
1901
1902 case SUBSTR: {
1903 const auto *LHSs = dyn_cast<StringInit>(LHS);
1904 const auto *MHSi = dyn_cast<IntInit>(MHS);
1905 const auto *RHSi = dyn_cast<IntInit>(RHS);
1906 if (LHSs && MHSi && RHSi) {
1907 int64_t StringSize = LHSs->getValue().size();
1908 int64_t Start = MHSi->getValue();
1909 int64_t Length = RHSi->getValue();
1910 if (Start < 0 || Start > StringSize)
1911 PrintError(CurRec->getLoc(),
1912 Twine("!substr start position is out of range 0...") +
1913 std::to_string(StringSize) + ": " +
1914 std::to_string(Start));
1915 if (Length < 0)
1916 PrintError(CurRec->getLoc(), "!substr length must be nonnegative");
1917 return StringInit::get(RK, LHSs->getValue().substr(Start, Length),
1918 LHSs->getFormat());
1919 }
1920 break;
1921 }
1922
1923 case FIND: {
1924 const auto *LHSs = dyn_cast<StringInit>(LHS);
1925 const auto *MHSs = dyn_cast<StringInit>(MHS);
1926 const auto *RHSi = dyn_cast<IntInit>(RHS);
1927 if (LHSs && MHSs && RHSi) {
1928 int64_t SourceSize = LHSs->getValue().size();
1929 int64_t Start = RHSi->getValue();
1930 if (Start < 0 || Start > SourceSize)
1931 PrintError(CurRec->getLoc(),
1932 Twine("!find start position is out of range 0...") +
1933 std::to_string(SourceSize) + ": " +
1934 std::to_string(Start));
1935 auto I = LHSs->getValue().find(MHSs->getValue(), Start);
1936 if (I == std::string::npos)
1937 return IntInit::get(RK, -1);
1938 return IntInit::get(RK, I);
1939 }
1940 break;
1941 }
1942
1943 case SETDAGARG: {
1944 const auto *Dag = dyn_cast<DagInit>(LHS);
1945 if (Dag && isa<IntInit, StringInit>(MHS)) {
1946 std::string Error;
1947 auto ArgNo = getDagArgNoByKey(Dag, MHS, Error);
1948 if (!ArgNo)
1949 PrintFatalError(CurRec->getLoc(), "!setdagarg " + Error);
1950
1951 assert(*ArgNo < Dag->getNumArgs());
1952
1953 SmallVector<const Init *, 8> Args(Dag->getArgs());
1954 Args[*ArgNo] = RHS;
1955 return DagInit::get(Dag->getOperator(), Dag->getName(), Args,
1956 Dag->getArgNames());
1957 }
1958 break;
1959 }
1960
1961 case SETDAGNAME: {
1962 const auto *Dag = dyn_cast<DagInit>(LHS);
1963 if (Dag && isa<IntInit, StringInit>(MHS)) {
1964 std::string Error;
1965 auto ArgNo = getDagArgNoByKey(Dag, MHS, Error);
1966 if (!ArgNo)
1967 PrintFatalError(CurRec->getLoc(), "!setdagname " + Error);
1968
1969 assert(*ArgNo < Dag->getNumArgs());
1970
1971 SmallVector<const StringInit *, 8> Names(Dag->getArgNames());
1972 Names[*ArgNo] = dyn_cast<StringInit>(RHS);
1973 return DagInit::get(Dag->getOperator(), Dag->getName(), Dag->getArgs(),
1974 Names);
1975 }
1976 break;
1977 }
1978 }
1979
1980 return this;
1981}
1982
1984 const Init *lhs = LHS->resolveReferences(R);
1985
1986 if (getOpcode() == IF && lhs != LHS) {
1987 if (const auto *Value = dyn_cast_or_null<IntInit>(
1989 // Short-circuit
1990 if (Value->getValue())
1991 return MHS->resolveReferences(R);
1992 return RHS->resolveReferences(R);
1993 }
1994 }
1995
1996 const Init *mhs = MHS->resolveReferences(R);
1997 const Init *rhs;
1998
1999 if (getOpcode() == FOREACH || getOpcode() == FILTER || getOpcode() == SORT) {
2000 ShadowResolver SR(R);
2001 SR.addShadow(lhs);
2002 rhs = RHS->resolveReferences(SR);
2003 } else {
2004 rhs = RHS->resolveReferences(R);
2005 }
2006
2007 if (LHS != lhs || MHS != mhs || RHS != rhs)
2008 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs, getType()))
2009 ->Fold(R.getCurrentRecord());
2010 return this;
2011}
2012
2013std::string TernOpInit::getAsString() const {
2014 std::string Result;
2015 bool UnquotedLHS = false;
2016 switch (getOpcode()) {
2017 case DAG: Result = "!dag"; break;
2018 case FILTER: Result = "!filter"; UnquotedLHS = true; break;
2019 case FOREACH: Result = "!foreach"; UnquotedLHS = true; break;
2020 case SORT:
2021 Result = "!sort";
2022 UnquotedLHS = true;
2023 break;
2024 case IF: Result = "!if"; break;
2025 case RANGE:
2026 Result = "!range";
2027 break;
2028 case SUBST: Result = "!subst"; break;
2029 case SUBSTR: Result = "!substr"; break;
2030 case FIND: Result = "!find"; break;
2031 case SETDAGARG:
2032 Result = "!setdagarg";
2033 break;
2034 case SETDAGNAME:
2035 Result = "!setdagname";
2036 break;
2037 }
2038 return (Result + "(" +
2039 (UnquotedLHS ? LHS->getAsUnquotedString() : LHS->getAsString()) +
2040 ", " + MHS->getAsString() + ", " + RHS->getAsString() + ")");
2041}
2042
2043static void ProfileFoldOpInit(FoldingSetNodeID &ID, const Init *Start,
2044 const Init *List, const Init *A, const Init *B,
2045 const Init *Expr, const RecTy *Type) {
2046 ID.AddPointer(Start);
2047 ID.AddPointer(List);
2048 ID.AddPointer(A);
2049 ID.AddPointer(B);
2050 ID.AddPointer(Expr);
2051 ID.AddPointer(Type);
2052}
2053
2054const FoldOpInit *FoldOpInit::get(const Init *Start, const Init *List,
2055 const Init *A, const Init *B,
2056 const Init *Expr, const RecTy *Type) {
2058 ProfileFoldOpInit(ID, Start, List, A, B, Expr, Type);
2059
2060 detail::RecordKeeperImpl &RK = Start->getRecordKeeper().getImpl();
2062 if (const FoldOpInit *I = RK.TheFoldOpInitPool.lookup(ID, Token))
2063 return I;
2064
2065 FoldOpInit *I = new (RK.Allocator) FoldOpInit(Start, List, A, B, Expr, Type);
2066 RK.TheFoldOpInitPool.insert(I, Token);
2067 return I;
2068}
2069
2071 ProfileFoldOpInit(ID, Start, List, A, B, Expr, getType());
2072}
2073
2074const Init *FoldOpInit::Fold(const Record *CurRec) const {
2075 if (const auto *LI = dyn_cast<ListInit>(List)) {
2076 const Init *Accum = Start;
2077 for (const Init *Elt : *LI) {
2078 MapResolver R(CurRec);
2079 R.set(A, Accum);
2080 R.set(B, Elt);
2081 Accum = Expr->resolveReferences(R);
2082 }
2083 return Accum;
2084 }
2085 return this;
2086}
2087
2089 const Init *NewStart = Start->resolveReferences(R);
2090 const Init *NewList = List->resolveReferences(R);
2091 ShadowResolver SR(R);
2092 SR.addShadow(A);
2093 SR.addShadow(B);
2094 const Init *NewExpr = Expr->resolveReferences(SR);
2095
2096 if (Start == NewStart && List == NewList && Expr == NewExpr)
2097 return this;
2098
2099 return get(NewStart, NewList, A, B, NewExpr, getType())
2100 ->Fold(R.getCurrentRecord());
2101}
2102
2103const Init *FoldOpInit::getBit(unsigned Bit) const {
2104 if (isa<BitRecTy>(getType()))
2105 return this;
2106 return VarBitInit::get(this, Bit);
2107}
2108
2109std::string FoldOpInit::getAsString() const {
2110 return (Twine("!foldl(") + Start->getAsString() + ", " + List->getAsString() +
2111 ", " + A->getAsUnquotedString() + ", " + B->getAsUnquotedString() +
2112 ", " + Expr->getAsString() + ")")
2113 .str();
2114}
2115
2117 const Init *Expr) {
2118 ID.AddPointer(CheckType);
2119 ID.AddPointer(Expr);
2120}
2121
2122const IsAOpInit *IsAOpInit::get(const RecTy *CheckType, const Init *Expr) {
2123
2125 ProfileIsAOpInit(ID, CheckType, Expr);
2126
2127 detail::RecordKeeperImpl &RK = Expr->getRecordKeeper().getImpl();
2129 if (const IsAOpInit *I = RK.TheIsAOpInitPool.lookup(ID, Token))
2130 return I;
2131
2132 IsAOpInit *I = new (RK.Allocator) IsAOpInit(CheckType, Expr);
2133 RK.TheIsAOpInitPool.insert(I, Token);
2134 return I;
2135}
2136
2138 ProfileIsAOpInit(ID, CheckType, Expr);
2139}
2140
2141const Init *IsAOpInit::Fold() const {
2142 if (const auto *TI = dyn_cast<TypedInit>(Expr)) {
2143 // Is the expression type known to be (a subclass of) the desired type?
2144 if (TI->getType()->typeIsConvertibleTo(CheckType))
2145 return IntInit::get(getRecordKeeper(), 1);
2146
2147 if (isa<RecordRecTy>(CheckType)) {
2148 // If the target type is not a subclass of the expression type once the
2149 // expression has been made concrete, or if the expression has fully
2150 // resolved to a record, we know that it can't be of the required type.
2151 if ((!CheckType->typeIsConvertibleTo(TI->getType()) &&
2152 Expr->isConcrete()) ||
2153 isa<DefInit>(Expr))
2154 return IntInit::get(getRecordKeeper(), 0);
2155 } else {
2156 // We treat non-record types as not castable.
2157 return IntInit::get(getRecordKeeper(), 0);
2158 }
2159 }
2160 return this;
2161}
2162
2164 const Init *NewExpr = Expr->resolveReferences(R);
2165 if (Expr != NewExpr)
2166 return get(CheckType, NewExpr)->Fold();
2167 return this;
2168}
2169
2170const Init *IsAOpInit::getBit(unsigned Bit) const {
2171 return VarBitInit::get(this, Bit);
2172}
2173
2174std::string IsAOpInit::getAsString() const {
2175 return (Twine("!isa<") + CheckType->getAsString() + ">(" +
2176 Expr->getAsString() + ")")
2177 .str();
2178}
2179
2181 const Init *Expr) {
2182 ID.AddPointer(CheckType);
2183 ID.AddPointer(Expr);
2184}
2185
2186const ExistsOpInit *ExistsOpInit::get(const RecTy *CheckType,
2187 const Init *Expr) {
2189 ProfileExistsOpInit(ID, CheckType, Expr);
2190
2191 detail::RecordKeeperImpl &RK = Expr->getRecordKeeper().getImpl();
2193 if (const ExistsOpInit *I = RK.TheExistsOpInitPool.lookup(ID, Token))
2194 return I;
2195
2196 ExistsOpInit *I = new (RK.Allocator) ExistsOpInit(CheckType, Expr);
2197 RK.TheExistsOpInitPool.insert(I, Token);
2198 return I;
2199}
2200
2202 ProfileExistsOpInit(ID, CheckType, Expr);
2203}
2204
2205const Init *ExistsOpInit::Fold(const Record *CurRec, bool IsFinal) const {
2206 if (const auto *Name = dyn_cast<StringInit>(Expr)) {
2207 // Look up all defined records to see if we can find one.
2208 const Record *D = CheckType->getRecordKeeper().getDef(Name->getValue());
2209 if (D) {
2210 // Check if types are compatible.
2212 D->getDefInit()->getType()->typeIsA(CheckType));
2213 }
2214
2215 if (CurRec) {
2216 // Self-references are allowed, but their resolution is delayed until
2217 // the final resolve to ensure that we get the correct type for them.
2218 auto *Anonymous = dyn_cast<AnonymousNameInit>(CurRec->getNameInit());
2219 if (Name == CurRec->getNameInit() ||
2220 (Anonymous && Name == Anonymous->getNameInit())) {
2221 if (!IsFinal)
2222 return this;
2223
2224 // No doubt that there exists a record, so we should check if types are
2225 // compatible.
2227 CurRec->getType()->typeIsA(CheckType));
2228 }
2229 }
2230
2231 if (IsFinal)
2232 return IntInit::get(getRecordKeeper(), 0);
2233 }
2234 return this;
2235}
2236
2238 const Init *NewExpr = Expr->resolveReferences(R);
2239 if (Expr != NewExpr || R.isFinal())
2240 return get(CheckType, NewExpr)->Fold(R.getCurrentRecord(), R.isFinal());
2241 return this;
2242}
2243
2244const Init *ExistsOpInit::getBit(unsigned Bit) const {
2245 return VarBitInit::get(this, Bit);
2246}
2247
2248std::string ExistsOpInit::getAsString() const {
2249 return (Twine("!exists<") + CheckType->getAsString() + ">(" +
2250 Expr->getAsString() + ")")
2251 .str();
2252}
2253
2255 const Init *Regex) {
2256 ID.AddPointer(Type);
2257 ID.AddPointer(Regex);
2258}
2259
2260const InstancesOpInit *InstancesOpInit::get(const RecTy *Type,
2261 const Init *Regex) {
2263 ProfileInstancesOpInit(ID, Type, Regex);
2264
2265 detail::RecordKeeperImpl &RK = Regex->getRecordKeeper().getImpl();
2267 if (const InstancesOpInit *I = RK.TheInstancesOpInitPool.lookup(ID, Token))
2268 return I;
2269
2270 InstancesOpInit *I = new (RK.Allocator) InstancesOpInit(Type, Regex);
2271 RK.TheInstancesOpInitPool.insert(I, Token);
2272 return I;
2273}
2274
2276 ProfileInstancesOpInit(ID, Type, Regex);
2277}
2278
2279const Init *InstancesOpInit::Fold(const Record *CurRec, bool IsFinal) const {
2280 if (CurRec && !IsFinal)
2281 return this;
2282
2283 const auto *RegexInit = dyn_cast<StringInit>(Regex);
2284 if (!RegexInit)
2285 return this;
2286
2287 StringRef RegexStr = RegexInit->getValue();
2288 llvm::Regex Matcher(RegexStr);
2289 if (!Matcher.isValid())
2290 PrintFatalError(Twine("invalid regex '") + RegexStr + Twine("'"));
2291
2292 const RecordKeeper &RK = Type->getRecordKeeper();
2293 SmallVector<Init *, 8> Selected;
2294 for (auto &Def : RK.getAllDerivedDefinitionsIfDefined(Type->getAsString()))
2295 if (Matcher.match(Def->getName()))
2296 Selected.push_back(Def->getDefInit());
2297
2298 return ListInit::get(Selected, Type);
2299}
2300
2302 const Init *NewRegex = Regex->resolveReferences(R);
2303 if (Regex != NewRegex || R.isFinal())
2304 return get(Type, NewRegex)->Fold(R.getCurrentRecord(), R.isFinal());
2305 return this;
2306}
2307
2308std::string InstancesOpInit::getAsString() const {
2309 return "!instances<" + Type->getAsString() + ">(" + Regex->getAsString() +
2310 ")";
2311}
2312
2313const RecTy *TypedInit::getFieldType(const StringInit *FieldName) const {
2314 if (const auto *RecordType = dyn_cast<RecordRecTy>(getType())) {
2315 for (const Record *Rec : RecordType->getClasses()) {
2316 if (const RecordVal *Field = Rec->getValue(FieldName))
2317 return Field->getType();
2318 }
2319 }
2320 return nullptr;
2321}
2322
2324 if (getType()->typeIsA(Ty))
2325 return this;
2326
2327 if (isa<BitRecTy>(getType()) && isa<BitsRecTy>(Ty) &&
2328 cast<BitsRecTy>(Ty)->getNumBits() == 1)
2329 return BitsInit::get(getRecordKeeper(), {this});
2330
2331 return nullptr;
2332}
2333
2334const Init *
2336 const auto *T = dyn_cast<BitsRecTy>(getType());
2337 if (!T) return nullptr; // Cannot subscript a non-bits variable.
2338 unsigned NumBits = T->getNumBits();
2339
2341 NewBits.reserve(Bits.size());
2342 for (unsigned Bit : Bits) {
2343 if (Bit >= NumBits)
2344 return nullptr;
2345
2346 NewBits.push_back(VarBitInit::get(this, Bit));
2347 }
2348 return BitsInit::get(getRecordKeeper(), NewBits);
2349}
2350
2351const Init *TypedInit::getCastTo(const RecTy *Ty) const {
2352 // Handle the common case quickly
2353 if (getType()->typeIsA(Ty))
2354 return this;
2355
2356 if (const Init *Converted = convertInitializerTo(Ty)) {
2357 assert(!isa<TypedInit>(Converted) ||
2358 cast<TypedInit>(Converted)->getType()->typeIsA(Ty));
2359 return Converted;
2360 }
2361
2362 if (!getType()->typeIsConvertibleTo(Ty))
2363 return nullptr;
2364
2365 return UnOpInit::get(UnOpInit::CAST, this, Ty)->Fold(nullptr);
2366}
2367
2368const VarInit *VarInit::get(StringRef VN, const RecTy *T) {
2369 const Init *Value = StringInit::get(T->getRecordKeeper(), VN);
2370 return VarInit::get(Value, T);
2371}
2372
2373const VarInit *VarInit::get(const Init *VN, const RecTy *T) {
2374 detail::RecordKeeperImpl &RK = T->getRecordKeeper().getImpl();
2375 VarInit *&I = RK.TheVarInitPool[{T, VN}];
2376 if (!I)
2377 I = new (RK.Allocator) VarInit(VN, T);
2378 return I;
2379}
2380
2382 const auto *NameString = cast<StringInit>(getNameInit());
2383 return NameString->getValue();
2384}
2385
2386const Init *VarInit::getBit(unsigned Bit) const {
2387 if (isa<BitRecTy>(getType()))
2388 return this;
2389 return VarBitInit::get(this, Bit);
2390}
2391
2393 if (const Init *Val = R.resolve(VarName))
2394 return Val;
2395 return this;
2396}
2397
2398const VarBitInit *VarBitInit::get(const TypedInit *T, unsigned B) {
2399 detail::RecordKeeperImpl &RK = T->getRecordKeeper().getImpl();
2400 VarBitInit *&I = RK.TheVarBitInitPool[{T, B}];
2401 if (!I)
2402 I = new (RK.Allocator) VarBitInit(T, B);
2403 return I;
2404}
2405
2406std::string VarBitInit::getAsString() const {
2407 return TI->getAsString() + "{" + utostr(Bit) + "}";
2408}
2409
2411 const Init *I = TI->resolveReferences(R);
2412 if (TI != I)
2413 return I->getBit(getBitNum());
2414
2415 return this;
2416}
2417
2418DefInit::DefInit(const Record *D)
2419 : TypedInit(IK_DefInit, D->getType()), Def(D) {}
2420
2422 if (auto *RRT = dyn_cast<RecordRecTy>(Ty))
2423 if (getType()->typeIsConvertibleTo(RRT))
2424 return this;
2425 return nullptr;
2426}
2427
2428const RecTy *DefInit::getFieldType(const StringInit *FieldName) const {
2429 if (const RecordVal *RV = Def->getValue(FieldName))
2430 return RV->getType();
2431 return nullptr;
2432}
2433
2434std::string DefInit::getAsString() const { return Def->getName().str(); }
2435
2436static void ProfileVarDefInit(FoldingSetNodeID &ID, const Record *Class,
2438 ID.AddInteger(Args.size());
2439 ID.AddPointer(Class);
2440
2441 for (const Init *I : Args)
2442 ID.AddPointer(I);
2443}
2444
2445VarDefInit::VarDefInit(SMLoc Loc, const Record *Class,
2447 : TypedInit(IK_VarDefInit, RecordRecTy::get(Class)), Loc(Loc), Class(Class),
2448 NumArgs(Args.size()) {
2449 llvm::uninitialized_copy(Args, getTrailingObjects());
2450}
2451
2452const VarDefInit *VarDefInit::get(SMLoc Loc, const Record *Class,
2455 ProfileVarDefInit(ID, Class, Args);
2456
2457 detail::RecordKeeperImpl &RK = Class->getRecords().getImpl();
2459 if (const VarDefInit *I = RK.TheVarDefInitPool.lookup(ID, Token))
2460 return I;
2461
2462 void *Mem = RK.Allocator.Allocate(
2463 totalSizeToAlloc<const ArgumentInit *>(Args.size()), alignof(VarDefInit));
2464 VarDefInit *I = new (Mem) VarDefInit(Loc, Class, Args);
2465 RK.TheVarDefInitPool.insert(I, Token);
2466 return I;
2467}
2468
2470 ProfileVarDefInit(ID, Class, args());
2471}
2472
2473const DefInit *VarDefInit::instantiate() {
2474 if (Def)
2475 return Def;
2476
2477 RecordKeeper &Records = Class->getRecords();
2478 auto NewRecOwner = std::make_unique<Record>(
2479 Records.getNewAnonymousName(), Loc, Records, Record::RK_AnonymousDef);
2480 Record *NewRec = NewRecOwner.get();
2481
2482 // Copy values from class to instance
2483 for (const RecordVal &Val : Class->getValues())
2484 NewRec->addValue(Val);
2485
2486 // Copy assertions from class to instance.
2487 NewRec->appendAssertions(Class);
2488
2489 // Copy dumps from class to instance.
2490 NewRec->appendDumps(Class);
2491
2492 // Substitute and resolve template arguments
2493 ArrayRef<const Init *> TArgs = Class->getTemplateArgs();
2494 MapResolver R(NewRec);
2495
2496 for (const Init *Arg : TArgs) {
2497 R.set(Arg, NewRec->getValue(Arg)->getValue());
2498 NewRec->removeValue(Arg);
2499 }
2500
2501 for (auto *Arg : args()) {
2502 if (Arg->isPositional())
2503 R.set(TArgs[Arg->getIndex()], Arg->getValue());
2504 if (Arg->isNamed())
2505 R.set(Arg->getName(), Arg->getValue());
2506 }
2507
2508 NewRec->resolveReferences(R);
2509
2510 // Add superclass.
2511 NewRec->addDirectSuperClass(
2512 Class, SMRange(Class->getLoc().back(), Class->getLoc().back()));
2513
2514 // Resolve internal references and store in record keeper
2515 NewRec->resolveReferences();
2516 Records.addDef(std::move(NewRecOwner));
2517
2518 // Check the assertions.
2519 NewRec->checkRecordAssertions();
2520
2521 // Check the assertions.
2522 NewRec->emitRecordDumps();
2523
2524 return Def = NewRec->getDefInit();
2525}
2526
2529 bool Changed = false;
2531 NewArgs.reserve(args_size());
2532
2533 for (const ArgumentInit *Arg : args()) {
2534 const auto *NewArg = cast<ArgumentInit>(Arg->resolveReferences(UR));
2535 NewArgs.push_back(NewArg);
2536 Changed |= NewArg != Arg;
2537 }
2538
2539 if (Changed) {
2540 auto *New = VarDefInit::get(Loc, Class, NewArgs);
2541 if (!UR.foundUnresolved())
2542 return const_cast<VarDefInit *>(New)->instantiate();
2543 return New;
2544 }
2545 return this;
2546}
2547
2548const Init *VarDefInit::Fold() const {
2549 if (Def)
2550 return Def;
2551
2553 for (const Init *Arg : args())
2554 Arg->resolveReferences(R);
2555
2556 if (!R.foundUnresolved())
2557 return const_cast<VarDefInit *>(this)->instantiate();
2558 return this;
2559}
2560
2561std::string VarDefInit::getAsString() const {
2562 std::string Result = Class->getNameInitAsString() + "<";
2563 ListSeparator LS;
2564 for (const Init *Arg : args()) {
2565 Result += LS;
2566 Result += Arg->getAsString();
2567 }
2568 return Result + ">";
2569}
2570
2571const FieldInit *FieldInit::get(const Init *R, const StringInit *FN) {
2572 detail::RecordKeeperImpl &RK = R->getRecordKeeper().getImpl();
2573 FieldInit *&I = RK.TheFieldInitPool[{R, FN}];
2574 if (!I)
2575 I = new (RK.Allocator) FieldInit(R, FN);
2576 return I;
2577}
2578
2579const Init *FieldInit::getBit(unsigned Bit) const {
2580 if (isa<BitRecTy>(getType()))
2581 return this;
2582 return VarBitInit::get(this, Bit);
2583}
2584
2586 const Init *NewRec = Rec->resolveReferences(R);
2587 if (NewRec != Rec)
2588 return FieldInit::get(NewRec, FieldName)->Fold(R.getCurrentRecord());
2589 return this;
2590}
2591
2592const Init *FieldInit::Fold(const Record *CurRec) const {
2593 if (const auto *DI = dyn_cast<DefInit>(Rec)) {
2594 const Record *Def = DI->getDef();
2595 if (Def == CurRec)
2596 PrintFatalError(CurRec->getLoc(),
2597 Twine("Attempting to access field '") +
2598 FieldName->getAsUnquotedString() + "' of '" +
2599 Rec->getAsString() + "' is a forbidden self-reference");
2600 const Init *FieldVal = Def->getValue(FieldName)->getValue();
2601 if (FieldVal->isConcrete())
2602 return FieldVal;
2603 }
2604 return this;
2605}
2606
2608 if (const auto *DI = dyn_cast<DefInit>(Rec)) {
2609 const Init *FieldVal = DI->getDef()->getValue(FieldName)->getValue();
2610 return FieldVal->isConcrete();
2611 }
2612 return false;
2613}
2614
2618 const RecTy *ValType) {
2619 assert(Conds.size() == Vals.size() &&
2620 "Number of conditions and values must match!");
2621 ID.AddPointer(ValType);
2622
2623 for (const auto &[Cond, Val] : zip(Conds, Vals)) {
2624 ID.AddPointer(Cond);
2625 ID.AddPointer(Val);
2626 }
2627}
2628
2629CondOpInit::CondOpInit(ArrayRef<const Init *> Conds,
2631 : TypedInit(IK_CondOpInit, Type), NumConds(Conds.size()), ValType(Type) {
2632 const Init **TrailingObjects = getTrailingObjects();
2635}
2636
2638 ProfileCondOpInit(ID, getConds(), getVals(), ValType);
2639}
2640
2643 const RecTy *Ty) {
2644 assert(Conds.size() == Values.size() &&
2645 "Number of conditions and values must match!");
2646
2648 ProfileCondOpInit(ID, Conds, Values, Ty);
2649
2650 detail::RecordKeeperImpl &RK = Ty->getRecordKeeper().getImpl();
2652 if (const CondOpInit *I = RK.TheCondOpInitPool.lookup(ID, Token))
2653 return I;
2654
2655 void *Mem = RK.Allocator.Allocate(
2656 totalSizeToAlloc<const Init *>(2 * Conds.size()), alignof(CondOpInit));
2657 CondOpInit *I = new (Mem) CondOpInit(Conds, Values, Ty);
2658 RK.TheCondOpInitPool.insert(I, Token);
2659 return I;
2660}
2661
2665
2666 bool Changed = false;
2667 for (auto [Cond, Val] : getCondAndVals()) {
2668 const Init *NewCond = Cond->resolveReferences(R);
2669 NewConds.push_back(NewCond);
2670 Changed |= NewCond != Cond;
2671
2672 const Init *NewVal = Val->resolveReferences(R);
2673 NewVals.push_back(NewVal);
2674 Changed |= NewVal != Val;
2675
2676 // Short-circuit if this cond is true.
2677 if (auto *NewCondVal = dyn_cast_or_null<IntInit>(
2679 if (NewCondVal->getValue()) {
2680 Changed = true;
2681 // Don't push the rest of the conds and values.
2682 break;
2683 }
2684 }
2685 }
2686
2687 if (Changed)
2688 return (CondOpInit::get(NewConds, NewVals,
2689 getValType()))->Fold(R.getCurrentRecord());
2690
2691 return this;
2692}
2693
2694const Init *CondOpInit::Fold(const Record *CurRec) const {
2696 for (auto [Cond, Val] : getCondAndVals()) {
2697 if (const auto *CondI = dyn_cast_or_null<IntInit>(
2698 Cond->convertInitializerTo(IntRecTy::get(RK)))) {
2699 if (CondI->getValue())
2700 return Val->convertInitializerTo(getValType());
2701 } else {
2702 return this;
2703 }
2704 }
2705
2706 PrintFatalError(CurRec->getLoc(),
2707 CurRec->getNameInitAsString() +
2708 " does not have any true condition in:" +
2709 this->getAsString());
2710 return nullptr;
2711}
2712
2714 return all_of(getCondAndVals(), [](const auto &Pair) {
2715 return std::get<0>(Pair)->isConcrete() && std::get<1>(Pair)->isConcrete();
2716 });
2717}
2718
2720 return all_of(getCondAndVals(), [](const auto &Pair) {
2721 return std::get<0>(Pair)->isComplete() && std::get<1>(Pair)->isComplete();
2722 });
2723}
2724
2725std::string CondOpInit::getAsString() const {
2726 std::string Result = "!cond(";
2727 ListSeparator LS;
2728 for (auto [Cond, Val] : getCondAndVals()) {
2729 Result += LS;
2730 Result += Cond->getAsString() + ": ";
2731 Result += Val->getAsString();
2732 }
2733 return Result + ")";
2734}
2735
2736const Init *CondOpInit::getBit(unsigned Bit) const {
2737 if (isa<BitRecTy>(getType()))
2738 return this;
2739 return VarBitInit::get(this, Bit);
2740}
2741
2742static void ProfileDagInit(FoldingSetNodeID &ID, const Init *V,
2743 const StringInit *VN, ArrayRef<const Init *> Args,
2745 ID.AddPointer(V);
2746 ID.AddPointer(VN);
2747
2748 for (auto [Arg, Name] : zip_equal(Args, ArgNames)) {
2749 ID.AddPointer(Arg);
2750 ID.AddPointer(Name);
2751 }
2752}
2753
2754DagInit::DagInit(const Init *V, const StringInit *VN,
2757 : TypedInit(IK_DagInit, DagRecTy::get(V->getRecordKeeper())), Val(V),
2758 ValName(VN), NumArgs(Args.size()) {
2759 llvm::uninitialized_copy(Args, getTrailingObjects<const Init *>());
2760 llvm::uninitialized_copy(ArgNames, getTrailingObjects<const StringInit *>());
2761}
2762
2763const DagInit *DagInit::get(const Init *V, const StringInit *VN,
2766 assert(Args.size() == ArgNames.size() &&
2767 "Number of DAG args and arg names must match!");
2768
2770 ProfileDagInit(ID, V, VN, Args, ArgNames);
2771
2772 detail::RecordKeeperImpl &RK = V->getRecordKeeper().getImpl();
2774 if (const DagInit *I = RK.TheDagInitPool.lookup(ID, Token))
2775 return I;
2776
2777 void *Mem =
2779 Args.size(), ArgNames.size()),
2780 alignof(DagInit));
2781 DagInit *I = new (Mem) DagInit(V, VN, Args, ArgNames);
2782 RK.TheDagInitPool.insert(I, Token);
2783 return I;
2784}
2785
2786const DagInit *DagInit::get(
2787 const Init *V, const StringInit *VN,
2788 ArrayRef<std::pair<const Init *, const StringInit *>> ArgAndNames) {
2791 return DagInit::get(V, VN, Args, Names);
2792}
2793
2795 ProfileDagInit(ID, Val, ValName, getArgs(), getArgNames());
2796}
2797
2799 if (const auto *DefI = dyn_cast<DefInit>(Val))
2800 return DefI->getDef();
2801 PrintFatalError(Loc, "Expected record as operator");
2802 return nullptr;
2803}
2804
2805std::optional<unsigned> DagInit::getArgNo(StringRef Name) const {
2807 auto It = llvm::find_if(ArgNames, [Name](const StringInit *ArgName) {
2808 return ArgName && ArgName->getValue() == Name;
2809 });
2810 if (It == ArgNames.end())
2811 return std::nullopt;
2812 return std::distance(ArgNames.begin(), It);
2813}
2814
2817 NewArgs.reserve(arg_size());
2818 bool ArgsChanged = false;
2819 for (const Init *Arg : getArgs()) {
2820 const Init *NewArg = Arg->resolveReferences(R);
2821 NewArgs.push_back(NewArg);
2822 ArgsChanged |= NewArg != Arg;
2823 }
2824
2825 const Init *Op = Val->resolveReferences(R);
2826 if (Op != Val || ArgsChanged)
2827 return DagInit::get(Op, ValName, NewArgs, getArgNames());
2828
2829 return this;
2830}
2831
2833 if (!Val->isConcrete())
2834 return false;
2835 return all_of(getArgs(), [](const Init *Elt) { return Elt->isConcrete(); });
2836}
2837
2838std::string DagInit::getAsString() const {
2839 std::string Result = "(" + Val->getAsString();
2840 if (ValName)
2841 Result += ":$" + ValName->getAsUnquotedString();
2842 if (!arg_empty()) {
2843 Result += " ";
2844 ListSeparator LS;
2845 for (auto [Arg, Name] : getArgAndNames()) {
2846 Result += LS;
2847 Result += Arg->getAsString();
2848 if (Name)
2849 Result += ":$" + Name->getAsUnquotedString();
2850 }
2851 }
2852 return Result + ")";
2853}
2854
2855//===----------------------------------------------------------------------===//
2856// Other implementations
2857//===----------------------------------------------------------------------===//
2858
2860 : Name(N), TyAndKind(T, K) {
2861 setValue(UnsetInit::get(N->getRecordKeeper()));
2862 assert(Value && "Cannot create unset value for current type!");
2863}
2864
2865// This constructor accepts the same arguments as the above, but also
2866// a source location.
2868 : Name(N), Loc(Loc), TyAndKind(T, K) {
2869 setValue(UnsetInit::get(N->getRecordKeeper()));
2870 assert(Value && "Cannot create unset value for current type!");
2871}
2872
2874 return cast<StringInit>(getNameInit())->getValue();
2875}
2876
2877std::string RecordVal::getPrintType() const {
2878 if (isa<StringRecTy>(getType())) {
2879 if (const auto *StrInit = dyn_cast<StringInit>(Value)) {
2880 if (StrInit->hasCodeFormat())
2881 return "code";
2882 else
2883 return "string";
2884 } else {
2885 return "string";
2886 }
2887 } else {
2888 return TyAndKind.getPointer()->getAsString();
2889 }
2890}
2891
2893 if (!V) {
2894 Value = nullptr;
2895 return false;
2896 }
2897
2898 const Init *NewValue = V->getCastTo(getType());
2899 if (!NewValue)
2900 return true;
2901
2902 Value = NewValue;
2903 assert(!isa<TypedInit>(Value) ||
2904 cast<TypedInit>(Value)->getType()->typeIsA(getType()));
2905 if (const auto *BTy = dyn_cast<BitsRecTy>(getType())) {
2906 if (isa<BitsInit>(Value))
2907 return false;
2908 SmallVector<const Init *, 64> Bits(BTy->getNumBits());
2909 for (unsigned I = 0, E = BTy->getNumBits(); I < E; ++I)
2910 Bits[I] = Value->getBit(I);
2911 Value = BitsInit::get(V->getRecordKeeper(), Bits);
2912 }
2913
2914 return false;
2915}
2916
2917// This version of setValue takes a source location and resets the
2918// location in the RecordVal.
2919bool RecordVal::setValue(const Init *V, SMLoc NewLoc) {
2920 Loc = NewLoc;
2921 return setValue(V);
2922}
2923
2924#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2925LLVM_DUMP_METHOD void RecordVal::dump() const { errs() << *this; }
2926#endif
2927
2928void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
2929 if (isNonconcreteOK()) OS << "field ";
2930 OS << getPrintType() << " " << getNameInitAsString();
2931
2932 if (getValue())
2933 OS << " = " << *getValue();
2934
2935 if (PrintSem) OS << ";\n";
2936}
2937
2939 assert(Locs.size() == 1);
2940 ForwardDeclarationLocs.push_back(Locs.front());
2941
2942 Locs.clear();
2943 Locs.push_back(Loc);
2944}
2945
2946void Record::checkName() {
2947 // Ensure the record name has string type.
2948 const auto *TypedName = cast<const TypedInit>(Name);
2949 if (!isa<StringRecTy>(TypedName->getType()))
2950 PrintFatalError(getLoc(), Twine("Record name '") + Name->getAsString() +
2951 "' is not a string!");
2952}
2953
2957 return RecordRecTy::get(TrackedRecords, DirectSCs);
2958}
2959
2961 if (!CorrespondingDefInit) {
2962 CorrespondingDefInit =
2963 new (TrackedRecords.getImpl().Allocator) DefInit(this);
2964 }
2965 return CorrespondingDefInit;
2966}
2967
2969 return RK.getImpl().LastRecordID++;
2970}
2971
2972void Record::setName(const Init *NewName) {
2973 Name = NewName;
2974 checkName();
2975 // DO NOT resolve record values to the name at this point because
2976 // there might be default values for arguments of this def. Those
2977 // arguments might not have been resolved yet so we don't want to
2978 // prematurely assume values for those arguments were not passed to
2979 // this def.
2980 //
2981 // Nonetheless, it may be that some of this Record's values
2982 // reference the record name. Indeed, the reason for having the
2983 // record name be an Init is to provide this flexibility. The extra
2984 // resolve steps after completely instantiating defs takes care of
2985 // this. See TGParser::ParseDef and TGParser::ParseDefm.
2986}
2987
2989 const Init *OldName = getNameInit();
2990 const Init *NewName = Name->resolveReferences(R);
2991 if (NewName != OldName) {
2992 // Re-register with RecordKeeper.
2993 setName(NewName);
2994 }
2995
2996 // Resolve the field values.
2997 for (RecordVal &Value : Values) {
2998 if (SkipVal == &Value) // Skip resolve the same field as the given one
2999 continue;
3000 if (const Init *V = Value.getValue()) {
3001 const Init *VR = V->resolveReferences(R);
3002 if (Value.setValue(VR)) {
3003 std::string Type;
3004 if (const auto *VRT = dyn_cast<TypedInit>(VR))
3005 Type =
3006 (Twine("of type '") + VRT->getType()->getAsString() + "' ").str();
3008 getLoc(),
3009 Twine("Invalid value ") + Type + "found when setting field '" +
3010 Value.getNameInitAsString() + "' of type '" +
3011 Value.getType()->getAsString() +
3012 "' after resolving references: " + VR->getAsUnquotedString() +
3013 "\n");
3014 }
3015 }
3016 }
3017
3018 // Resolve the assertion expressions.
3019 for (AssertionInfo &Assertion : Assertions) {
3020 const Init *Value = Assertion.Condition->resolveReferences(R);
3021 Assertion.Condition = Value;
3022 Value = Assertion.Message->resolveReferences(R);
3023 Assertion.Message = Value;
3024 }
3025 // Resolve the dump expressions.
3026 for (DumpInfo &Dump : Dumps) {
3027 const Init *Value = Dump.Message->resolveReferences(R);
3028 Dump.Message = Value;
3029 }
3030}
3031
3032void Record::resolveReferences(const Init *NewName) {
3033 RecordResolver R(*this);
3034 R.setName(NewName);
3035 R.setFinal(true);
3037}
3038
3039#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3040LLVM_DUMP_METHOD void Record::dump() const { errs() << *this; }
3041#endif
3042
3044 OS << R.getNameInitAsString();
3045
3046 ArrayRef<const Init *> TArgs = R.getTemplateArgs();
3047 if (!TArgs.empty()) {
3048 OS << "<";
3049 ListSeparator LS;
3050 for (const Init *TA : TArgs) {
3051 const RecordVal *RV = R.getValue(TA);
3052 assert(RV && "Template argument record not found??");
3053 OS << LS;
3054 RV->print(OS, false);
3055 }
3056 OS << ">";
3057 }
3058
3059 OS << " {";
3060 std::vector<const Record *> SCs = R.getSuperClasses();
3061 if (!SCs.empty()) {
3062 OS << "\t//";
3063 for (const Record *SC : SCs)
3064 OS << " " << SC->getNameInitAsString();
3065 }
3066 OS << "\n";
3067
3068 for (const RecordVal &Val : R.getValues())
3069 if (Val.isNonconcreteOK() && !R.isTemplateArg(Val.getNameInit()))
3070 OS << Val;
3071 for (const RecordVal &Val : R.getValues())
3072 if (!Val.isNonconcreteOK() && !R.isTemplateArg(Val.getNameInit()))
3073 OS << Val;
3074
3075 return OS << "}\n";
3076}
3077
3079 const RecordVal *R = getValue(FieldName);
3080 if (!R)
3081 PrintFatalError(getLoc(), "Record `" + getName() +
3082 "' does not have a field named `" + FieldName + "'!\n");
3083 return R->getLoc();
3084}
3085
3086const Init *Record::getValueInit(StringRef FieldName) const {
3087 const RecordVal *R = getValue(FieldName);
3088 if (!R || !R->getValue())
3089 PrintFatalError(getLoc(), "Record `" + getName() +
3090 "' does not have a field named `" + FieldName + "'!\n");
3091 return R->getValue();
3092}
3093
3095 const Init *I = getValueInit(FieldName);
3096 if (const auto *SI = dyn_cast<StringInit>(I))
3097 return SI->getValue();
3098 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +
3099 "' exists but does not have a string value");
3100}
3101
3102std::optional<StringRef>
3104 const RecordVal *R = getValue(FieldName);
3105 if (!R || !R->getValue())
3106 return std::nullopt;
3107 if (isa<UnsetInit>(R->getValue()))
3108 return std::nullopt;
3109
3110 if (const auto *SI = dyn_cast<StringInit>(R->getValue()))
3111 return SI->getValue();
3112
3114 "Record `" + getName() + "', ` field `" + FieldName +
3115 "' exists but does not have a string initializer!");
3116}
3117
3119 const Init *I = getValueInit(FieldName);
3120 if (const auto *BI = dyn_cast<BitsInit>(I))
3121 return BI;
3122 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +
3123 "' exists but does not have a bits value");
3124}
3125
3127 const Init *I = getValueInit(FieldName);
3128 if (const auto *LI = dyn_cast<ListInit>(I))
3129 return LI;
3130 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +
3131 "' exists but does not have a list value");
3132}
3133
3134std::vector<const Record *>
3136 const ListInit *List = getValueAsListInit(FieldName);
3137 std::vector<const Record *> Defs;
3138 for (const Init *I : List->getElements()) {
3139 if (const auto *DI = dyn_cast<DefInit>(I))
3140 Defs.push_back(DI->getDef());
3141 else
3142 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
3143 FieldName +
3144 "' list is not entirely DefInit!");
3145 }
3146 return Defs;
3147}
3148
3149int64_t Record::getValueAsInt(StringRef FieldName) const {
3150 const Init *I = getValueInit(FieldName);
3151 if (const auto *II = dyn_cast<IntInit>(I))
3152 return II->getValue();
3154 getLoc(),
3155 Twine("Record `") + getName() + "', field `" + FieldName +
3156 "' exists but does not have an int value: " + I->getAsString());
3157}
3158
3159std::vector<int64_t>
3161 const ListInit *List = getValueAsListInit(FieldName);
3162 std::vector<int64_t> Ints;
3163 for (const Init *I : List->getElements()) {
3164 if (const auto *II = dyn_cast<IntInit>(I))
3165 Ints.push_back(II->getValue());
3166 else
3168 Twine("Record `") + getName() + "', field `" + FieldName +
3169 "' exists but does not have a list of ints value: " +
3170 I->getAsString());
3171 }
3172 return Ints;
3173}
3174
3175std::vector<StringRef>
3177 const ListInit *List = getValueAsListInit(FieldName);
3178 std::vector<StringRef> Strings;
3179 for (const Init *I : List->getElements()) {
3180 if (const auto *SI = dyn_cast<StringInit>(I))
3181 Strings.push_back(SI->getValue());
3182 else
3184 Twine("Record `") + getName() + "', field `" + FieldName +
3185 "' exists but does not have a list of strings value: " +
3186 I->getAsString());
3187 }
3188 return Strings;
3189}
3190
3191const Record *Record::getValueAsDef(StringRef FieldName) const {
3192 const Init *I = getValueInit(FieldName);
3193 if (const auto *DI = dyn_cast<DefInit>(I))
3194 return DI->getDef();
3195 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
3196 FieldName + "' does not have a def initializer!");
3197}
3198
3200 const Init *I = getValueInit(FieldName);
3201 if (const auto *DI = dyn_cast<DefInit>(I))
3202 return DI->getDef();
3203 if (isa<UnsetInit>(I))
3204 return nullptr;
3205 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
3206 FieldName + "' does not have either a def initializer or '?'!");
3207}
3208
3209bool Record::getValueAsBit(StringRef FieldName) const {
3210 const Init *I = getValueInit(FieldName);
3211 if (const auto *BI = dyn_cast<BitInit>(I))
3212 return BI->getValue();
3213 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
3214 FieldName + "' does not have a bit initializer!");
3215}
3216
3217bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
3218 const Init *I = getValueInit(FieldName);
3219 if (isa<UnsetInit>(I)) {
3220 Unset = true;
3221 return false;
3222 }
3223 Unset = false;
3224 if (const auto *BI = dyn_cast<BitInit>(I))
3225 return BI->getValue();
3226 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
3227 FieldName + "' does not have a bit initializer!");
3228}
3229
3230const DagInit *Record::getValueAsDag(StringRef FieldName) const {
3231 const Init *I = getValueInit(FieldName);
3232 if (const auto *DI = dyn_cast<DagInit>(I))
3233 return DI;
3234 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
3235 FieldName + "' does not have a dag initializer!");
3236}
3237
3238// Check all record assertions: For each one, resolve the condition
3239// and message, then call CheckAssert().
3240// Note: The condition and message are probably already resolved,
3241// but resolving again allows calls before records are resolved.
3243 RecordResolver R(*this);
3244 R.setFinal(true);
3245
3246 bool AnyFailed = false;
3247 for (const auto &Assertion : getAssertions()) {
3248 const Init *Condition = Assertion.Condition->resolveReferences(R);
3249 const Init *Message = Assertion.Message->resolveReferences(R);
3250 AnyFailed |= CheckAssert(Assertion.Loc, Condition, Message);
3251 }
3252
3253 if (!AnyFailed)
3254 return;
3255
3256 // If any of the record assertions failed, print some context that will
3257 // help see where the record that caused these assert failures is defined.
3258 PrintError(this, "assertion failed in this record");
3259}
3260
3262 RecordResolver R(*this);
3263 R.setFinal(true);
3264
3265 for (const DumpInfo &Dump : getDumps()) {
3266 const Init *Message = Dump.Message->resolveReferences(R);
3267 dumpMessage(Dump.Loc, Message);
3268 }
3269}
3270
3271// Report a warning if the record has unused template arguments.
3273 for (const Init *TA : getTemplateArgs()) {
3274 const RecordVal *Arg = getValue(TA);
3275 if (!Arg->isUsed())
3276 PrintWarning(Arg->getLoc(),
3277 "unused template argument: " + Twine(Arg->getName()));
3278 }
3279}
3280
3282 : Impl(std::make_unique<detail::RecordKeeperImpl>(*this)),
3283 Timer(std::make_unique<TGTimer>()) {}
3284
3285RecordKeeper::~RecordKeeper() = default;
3286
3287#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3288LLVM_DUMP_METHOD void RecordKeeper::dump() const { errs() << *this; }
3289#endif
3290
3292 OS << "------------- Classes -----------------\n";
3293 for (const auto &[_, C] : RK.getClasses())
3294 OS << "class " << *C;
3295
3296 OS << "------------- Defs -----------------\n";
3297 for (const auto &[_, D] : RK.getDefs())
3298 OS << "def " << *D;
3299 return OS;
3300}
3301
3302/// GetNewAnonymousName - Generate a unique anonymous name that can be used as
3303/// an identifier.
3305 return AnonymousNameInit::get(*this, getImpl().AnonCounter++);
3306}
3307
3310 // We cache the record vectors for single classes. Many backends request
3311 // the same vectors multiple times.
3312 auto [Iter, Inserted] = Cache.try_emplace(ClassName.str());
3313 if (Inserted)
3314 Iter->second = getAllDerivedDefinitions(ArrayRef(ClassName));
3315 return Iter->second;
3316}
3317
3318std::vector<const Record *>
3321 std::vector<const Record *> Defs;
3322
3323 assert(ClassNames.size() > 0 && "At least one class must be passed.");
3324 for (StringRef ClassName : ClassNames) {
3325 const Record *Class = getClass(ClassName);
3326 if (!Class)
3327 PrintFatalError("The class '" + ClassName + "' is not defined\n");
3328 ClassRecs.push_back(Class);
3329 }
3330
3331 for (const auto &OneDef : getDefs()) {
3332 if (all_of(ClassRecs, [&OneDef](const Record *Class) {
3333 return OneDef.second->isSubClassOf(Class);
3334 }))
3335 Defs.push_back(OneDef.second.get());
3336 }
3337 llvm::sort(Defs, LessRecord());
3338 return Defs;
3339}
3340
3343 if (getClass(ClassName))
3344 return getAllDerivedDefinitions(ClassName);
3345 return Cache[""];
3346}
3347
3349 Impl->dumpAllocationStats(OS);
3350}
3351
3352const Init *MapResolver::resolve(const Init *VarName) {
3353 auto It = Map.find(VarName);
3354 if (It == Map.end())
3355 return nullptr;
3356
3357 const Init *I = It->second.V;
3358
3359 if (!It->second.Resolved && Map.size() > 1) {
3360 // Resolve mutual references among the mapped variables, but prevent
3361 // infinite recursion.
3362 Map.erase(It);
3363 I = I->resolveReferences(*this);
3364 Map[VarName] = {I, true};
3365 }
3366
3367 return I;
3368}
3369
3370const Init *RecordResolver::resolve(const Init *VarName) {
3371 const Init *Val = Cache.lookup(VarName);
3372 if (Val)
3373 return Val;
3374
3375 if (llvm::is_contained(Stack, VarName))
3376 return nullptr; // prevent infinite recursion
3377
3378 if (const RecordVal *RV = getCurrentRecord()->getValue(VarName)) {
3379 if (!isa<UnsetInit>(RV->getValue())) {
3380 Val = RV->getValue();
3381 Stack.push_back(VarName);
3382 Val = Val->resolveReferences(*this);
3383 Stack.pop_back();
3384 }
3385 } else if (Name && VarName == getCurrentRecord()->getNameInit()) {
3386 Stack.push_back(VarName);
3387 Val = Name->resolveReferences(*this);
3388 Stack.pop_back();
3389 }
3390
3391 Cache[VarName] = Val;
3392 return Val;
3393}
3394
3396 const Init *I = nullptr;
3397
3398 if (R) {
3399 I = R->resolve(VarName);
3400 if (I && !FoundUnresolved) {
3401 // Do not recurse into the resolved initializer, as that would change
3402 // the behavior of the resolver we're delegating, but do check to see
3403 // if there are unresolved variables remaining.
3405 I->resolveReferences(Sub);
3406 FoundUnresolved |= Sub.FoundUnresolved;
3407 }
3408 }
3409
3410 if (!I)
3411 FoundUnresolved = true;
3412 return I;
3413}
3414
3416 if (VarName == VarNameToTrack)
3417 Found = true;
3418 return nullptr;
3419}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
This file defines the DenseMap class.
This file defines a hash set that can be used to remove duplication of nodes in a graph.
#define _
static constexpr Value * getValue(Ty &ValueOrUse)
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#define T1
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
const SmallVectorImpl< MachineOperand > & Cond
static const Init * SortHelper(const Init *LHS, const Init *MHS, const Init *RHS, const RecTy *Type, const Record *CurRec)
Definition Record.cpp:1726
static void ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef< const Init * > Range)
Definition Record.cpp:456
static bool canFitInBitfield(int64_t Value, unsigned NumBits)
Definition Record.cpp:611
static void ProfileCondOpInit(FoldingSetNodeID &ID, ArrayRef< const Init * > Conds, ArrayRef< const Init * > Vals, const RecTy *ValType)
Definition Record.cpp:2615
static std::optional< unsigned > getDagArgNoByKey(const DagInit *Dag, const Init *Key, std::string &Error)
Definition Record.cpp:1223
static const StringInit * ConcatStringInits(const StringInit *I0, const StringInit *I1)
Definition Record.cpp:1066
static void ProfileExistsOpInit(FoldingSetNodeID &ID, const RecTy *CheckType, const Init *Expr)
Definition Record.cpp:2180
static const ListInit * ConcatListInits(const ListInit *LHS, const ListInit *RHS)
Definition Record.cpp:1127
static const StringInit * interleaveStringList(const ListInit *List, const StringInit *Delim)
Definition Record.cpp:1075
static void ProfileDagInit(FoldingSetNodeID &ID, const Init *V, const StringInit *VN, ArrayRef< const Init * > Args, ArrayRef< const StringInit * > ArgNames)
Definition Record.cpp:2742
static void ProfileFoldOpInit(FoldingSetNodeID &ID, const Init *Start, const Init *List, const Init *A, const Init *B, const Init *Expr, const RecTy *Type)
Definition Record.cpp:2043
static void ProfileInstancesOpInit(FoldingSetNodeID &ID, const RecTy *Type, const Init *Regex)
Definition Record.cpp:2254
static void ProfileArgumentInit(FoldingSetNodeID &ID, const Init *Value, ArgAuxType Aux)
Definition Record.cpp:398
static const Init * ForeachDagApply(const Init *LHS, const DagInit *MHSd, const Init *RHS, const Record *CurRec)
Definition Record.cpp:1652
static const Init * FilterHelper(const Init *LHS, const Init *MHS, const Init *RHS, const RecTy *Type, const Record *CurRec)
Definition Record.cpp:1701
static const Init * ItemApply(const Init *LHS, const Init *MHSe, const Init *RHS, const Record *CurRec)
Definition Record.cpp:1645
static const RecordRecTy * resolveRecordTypes(const RecordRecTy *T1, const RecordRecTy *T2)
Definition Record.cpp:324
static void ProfileRecordRecTy(FoldingSetNodeID &ID, ArrayRef< const Record * > Classes)
Definition Record.cpp:229
static const Init * ForeachHelper(const Init *LHS, const Init *MHS, const Init *RHS, const RecTy *Type, const Record *CurRec)
Definition Record.cpp:1679
static void ProfileVarDefInit(FoldingSetNodeID &ID, const Record *Class, ArrayRef< const ArgumentInit * > Args)
Definition Record.cpp:2436
static void ProfileIsAOpInit(FoldingSetNodeID &ID, const RecTy *CheckType, const Init *Expr)
Definition Record.cpp:2116
static const StringInit * interleaveIntList(const ListInit *List, const StringInit *Delim)
Definition Record.cpp:1096
This file defines the SmallString class.
This file defines the SmallVector class.
FunctionLoweringInfo::StatepointRelocationRecord RecordType
This file contains some functions that are useful when dealing with strings.
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static constexpr int Concat[]
Value * RHS
Value * LHS
static AnonymousNameInit * get(RecordKeeper &RK, unsigned)
Definition Record.cpp:656
const StringInit * getNameInit() const
Definition Record.cpp:660
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:668
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:664
const ArgumentInit * cloneWithValue(const Init *Value) const
Definition Record.h:529
void Profile(FoldingSetNodeID &ID) const
Definition Record.cpp:409
static const ArgumentInit * get(const Init *Value, ArgAuxType Aux)
Definition Record.cpp:413
ArgumentInit(const Init *Value, ArgAuxType Aux)
Definition Record.h:504
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:428
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static const BinOpInit * get(BinaryOp opc, const Init *lhs, const Init *rhs, const RecTy *Type)
Definition Record.cpp:1053
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:1554
static const Init * getStrConcat(const Init *lhs, const Init *rhs)
Definition Record.cpp:1118
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:1582
BinaryOp getOpcode() const
Definition Record.h:944
std::optional< bool > CompareInit(unsigned Opc, const Init *LHS, const Init *RHS) const
Definition Record.cpp:1145
static const Init * getListConcat(const TypedInit *lhs, const Init *rhs)
Definition Record.cpp:1135
const Init * Fold(const Record *CurRec) const
Definition Record.cpp:1255
'true'/'false' - Represent a concrete initializer for a bit.
Definition Record.h:557
static BitInit * get(RecordKeeper &RK, bool V)
Definition Record.cpp:436
bool getValue() const
Definition Record.h:575
const Init * convertInitializerTo(const RecTy *Ty) const override
Convert to a value whose type is Ty, or return null if this is not possible.
Definition Record.cpp:440
'bit' - Represent a single bit
Definition Record.h:114
static const BitRecTy * get(RecordKeeper &RK)
Definition Record.cpp:150
bool typeIsConvertibleTo(const RecTy *RHS) const override
Return true if all values of 'this' type can be converted to the specified type.
Definition Record.cpp:154
'{ a, b, c }' - Represents an initializer for a BitsRecTy value.
Definition Record.h:592
void Profile(FoldingSetNodeID &ID) const
Definition Record.cpp:486
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:552
bool isComplete() const override
Is this a complete value with no unset (uninitialized) subvalues?
Definition Record.cpp:542
unsigned getNumBits() const
Definition Record.h:613
std::optional< int64_t > convertInitializerToInt() const
Definition Record.cpp:512
const Init * getBit(unsigned Bit) const override
Get the Init value of the specified bit.
Definition Record.h:632
const Init * convertInitializerBitRange(ArrayRef< unsigned > Bits) const override
This function is used to implement the bit range selection operator.
Definition Record.cpp:531
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:567
const Init * convertInitializerTo(const RecTy *Ty) const override
Convert to a value whose type is Ty, or return null if this is not possible.
Definition Record.cpp:490
ArrayRef< const Init * > getBits() const
Definition Record.h:630
uint64_t convertKnownBitsToInt() const
Definition Record.cpp:522
bool allInComplete() const
Definition Record.cpp:545
static BitsInit * get(RecordKeeper &RK, ArrayRef< const Init * > Range)
Definition Record.cpp:470
bool isConcrete() const override
Is this a concrete and fully resolved value without any references or stuck operations?
Definition Record.cpp:548
'bits<n>' - Represent a fixed number of bits
Definition Record.h:132
bool typeIsConvertibleTo(const RecTy *RHS) const override
Return true if all values of 'this' type can be converted to the specified type.
Definition Record.cpp:176
static const BitsRecTy * get(RecordKeeper &RK, unsigned Sz)
Definition Record.cpp:162
std::string getAsString() const override
Definition Record.cpp:172
const Init * Fold(const Record *CurRec) const
Definition Record.cpp:2694
auto getCondAndVals() const
Definition Record.h:1066
ArrayRef< const Init * > getVals() const
Definition Record.h:1062
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:2662
const Init * getBit(unsigned Bit) const override
Get the Init value of the specified bit.
Definition Record.cpp:2736
bool isConcrete() const override
Is this a concrete and fully resolved value without any references or stuck operations?
Definition Record.cpp:2713
void Profile(FoldingSetNodeID &ID) const
Definition Record.cpp:2637
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2725
static const CondOpInit * get(ArrayRef< const Init * > Conds, ArrayRef< const Init * > Values, const RecTy *Type)
Definition Record.cpp:2641
const RecTy * getValType() const
Definition Record.h:1050
bool isComplete() const override
Is this a complete value with no unset (uninitialized) subvalues?
Definition Record.cpp:2719
ArrayRef< const Init * > getConds() const
Definition Record.h:1058
(v a, b) - Represent a DAG tree value.
Definition Record.h:1440
bool isConcrete() const override
Is this a concrete and fully resolved value without any references or stuck operations?
Definition Record.cpp:2832
std::optional< unsigned > getArgNo(StringRef Name) const
This method looks up the specified argument name and returns its argument number or std::nullopt if t...
Definition Record.cpp:2805
const StringInit * getName() const
Definition Record.h:1486
void Profile(FoldingSetNodeID &ID) const
Definition Record.cpp:2794
const Init * getOperator() const
Definition Record.h:1483
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:2815
ArrayRef< const StringInit * > getArgNames() const
Definition Record.h:1513
static const DagInit * get(const Init *V, const StringInit *VN, ArrayRef< const Init * > Args, ArrayRef< const StringInit * > ArgNames)
Definition Record.cpp:2763
size_t arg_size() const
Definition Record.h:1538
bool arg_empty() const
Definition Record.h:1539
const Record * getOperatorAsDef(ArrayRef< SMLoc > Loc) const
Definition Record.cpp:2798
auto getArgAndNames() const
Definition Record.h:1518
ArrayRef< const Init * > getArgs() const
Definition Record.h:1509
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2838
'dag' - Represent a dag fragment
Definition Record.h:214
std::string getAsString() const override
Definition Record.cpp:225
static const DagRecTy * get(RecordKeeper &RK)
Definition Record.cpp:221
AL - Represent a reference to a 'def' in the description.
Definition Record.h:1308
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2434
const RecTy * getFieldType(const StringInit *FieldName) const override
This function is used to implement the FieldInit class.
Definition Record.cpp:2428
const Init * convertInitializerTo(const RecTy *Ty) const override
Convert to a value whose type is Ty, or return null if this is not possible.
Definition Record.cpp:2421
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
void Profile(FoldingSetNodeID &ID) const
Definition Record.cpp:2201
static const ExistsOpInit * get(const RecTy *CheckType, const Init *Expr)
Definition Record.cpp:2186
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2248
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:2237
const Init * Fold(const Record *CurRec, bool IsFinal=false) const
Definition Record.cpp:2205
const Init * getBit(unsigned Bit) const override
Get the Init value of the specified bit.
Definition Record.cpp:2244
X.Y - Represent a reference to a subfield of a variable.
Definition Record.h:1394
const Init * Fold(const Record *CurRec) const
Definition Record.cpp:2592
const Init * getBit(unsigned Bit) const override
Get the Init value of the specified bit.
Definition Record.cpp:2579
static const FieldInit * get(const Init *R, const StringInit *FN)
Definition Record.cpp:2571
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:2585
bool isConcrete() const override
Is this a concrete and fully resolved value without any references or stuck operations?
Definition Record.cpp:2607
const Init * Fold(const Record *CurRec) const
Definition Record.cpp:2074
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2109
static const FoldOpInit * get(const Init *Start, const Init *List, const Init *A, const Init *B, const Init *Expr, const RecTy *Type)
Definition Record.cpp:2054
const Init * getBit(unsigned Bit) const override
Get the Init value of the specified bit.
Definition Record.cpp:2103
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:2088
void Profile(FoldingSetNodeID &ID) const
Definition Record.cpp:2070
void insert(T *N, FoldingSetInsertToken Token)
Insert the specified node into the folding set, knowing that it is not already in the folding set.
Definition FoldingSet.h:502
T * lookup(const FoldingSetNodeID &ID, FoldingSetInsertToken &Token)
Look up the node specified by ID.
Definition FoldingSet.h:493
Insertion token: a failed lookup fills it in, the matching insert consumes it.
Definition FoldingSet.h:295
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:171
const Init * resolve(const Init *VarName) override
Return the initializer for the given variable name (should normally be a StringInit),...
Definition Record.cpp:3415
virtual const Init * resolveReferences(Resolver &R) const
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.h:407
uint8_t Opc
Definition Record.h:336
virtual std::string getAsUnquotedString() const
Convert this value to a literal form, without adding quotes around a string.
Definition Record.h:371
void dump() const
Debugging method that may be called through a debugger; just invokes print on stderr.
Definition Record.cpp:377
void print(raw_ostream &OS) const
Print this value.
Definition Record.h:364
virtual std::string getAsString() const =0
Convert this value to a literal form.
virtual bool isConcrete() const
Is this a concrete and fully resolved value without any references or stuck operations?
Definition Record.h:361
virtual bool isComplete() const
Is this a complete value with no unset (uninitialized) subvalues?
Definition Record.h:357
virtual const Init * getBit(unsigned Bit) const =0
Get the Init value of the specified bit.
virtual const Init * convertInitializerTo(const RecTy *Ty) const =0
Convert to a value whose type is Ty, or return null if this is not possible.
virtual const Init * getCastTo(const RecTy *Ty) const =0
If this value is convertible to type Ty, return a value whose type is Ty, generating a !...
RecordKeeper & getRecordKeeper() const
Get the record keeper that initialized this Init.
Definition Record.cpp:380
Init(InitKind K, uint8_t Opc=0)
Definition Record.h:349
void Profile(FoldingSetNodeID &ID) const
Definition Record.cpp:2275
const Init * Fold(const Record *CurRec, bool IsFinal=false) const
Definition Record.cpp:2279
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:2301
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2308
static const InstancesOpInit * get(const RecTy *Type, const Init *Regex)
Definition Record.cpp:2260
static IntInit * get(RecordKeeper &RK, int64_t V)
Definition Record.cpp:600
const Init * convertInitializerBitRange(ArrayRef< unsigned > Bits) const override
This function is used to implement the bit range selection operator.
Definition Record.cpp:644
int64_t getValue() const
Definition Record.h:652
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:607
const Init * convertInitializerTo(const RecTy *Ty) const override
Convert to a value whose type is Ty, or return null if this is not possible.
Definition Record.cpp:617
'int' - Represent an integer value of no particular size
Definition Record.h:153
static const IntRecTy * get(RecordKeeper &RK)
Definition Record.cpp:183
bool typeIsConvertibleTo(const RecTy *RHS) const override
Return true if all values of 'this' type can be converted to the specified type.
Definition Record.cpp:187
static const IsAOpInit * get(const RecTy *CheckType, const Init *Expr)
Definition Record.cpp:2122
void Profile(FoldingSetNodeID &ID) const
Definition Record.cpp:2137
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:2163
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2174
const Init * getBit(unsigned Bit) const override
Get the Init value of the specified bit.
Definition Record.cpp:2170
const Init * Fold() const
Definition Record.cpp:2141
[AL, AH, CL] - Represent a list of defs
Definition Record.h:752
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:782
const RecTy * getElementType() const
Definition Record.h:787
static const ListInit * get(ArrayRef< const Init * > Range, const RecTy *EltTy)
Definition Record.cpp:702
bool isConcrete() const override
Is this a concrete and fully resolved value without any references or stuck operations?
Definition Record.cpp:777
bool isComplete() const override
Is this a complete value with no unset (uninitialized) subvalues?
Definition Record.cpp:772
const Init * resolveReferences(Resolver &R) const override
This method is used by classes that refer to other variables which may not be defined at the time the...
Definition Record.cpp:756
size_t size() const
Definition Record.h:809
const Init * convertInitializerTo(const RecTy *Ty) const override
Convert to a value whose type is Ty, or return null if this is not possible.
Definition Record.cpp:719
const Record * getElementAsRecord(unsigned Idx) const
Definition Record.cpp:748
ArrayRef< const Init * > getElements() const
Definition Record.h:774
const Init * getElement(unsigned Idx) const
Definition Record.h:781
'list<Ty>' - Represent a list of element values, all of which must be of the specified type.
Definition Record.h:190
const RecTy * getElementType() const
Definition Record.h:204
bool typeIsA(const RecTy *RHS) const override
Return true if 'this' type is equal to or a subtype of RHS.
Definition Record.cpp:215
std::string getAsString() const override
Definition Record.cpp:205
bool typeIsConvertibleTo(const RecTy *RHS) const override
Return true if all values of 'this' type can be converted to the specified type.
Definition Record.cpp:209
A helper class to return the specified delimiter string after the first invocation of operator String...
Resolve arbitrary mappings.
Definition Record.h:2241
const Init * resolve(const Init *VarName) override
Return the initializer for the given variable name (should normally be a StringInit),...
Definition Record.cpp:3352
const Init * getBit(unsigned Bit) const final
Get the Init value of the specified bit.
Definition Record.cpp:792
RecordKeeper & getRecordKeeper() const
Return the RecordKeeper that uniqued this Type.
Definition Record.h:90
virtual bool typeIsA(const RecTy *RHS) const
Return true if 'this' type is equal to or a subtype of RHS.
Definition Record.cpp:148
virtual bool typeIsConvertibleTo(const RecTy *RHS) const
Return true if all values of 'this' type can be converted to the specified type.
Definition Record.cpp:143
RecTyKind
Subclass discriminator (for dyn_cast<> et al.)
Definition Record.h:65
@ BitsRecTyKind
Definition Record.h:67
@ IntRecTyKind
Definition Record.h:68
@ StringRecTyKind
Definition Record.h:69
@ BitRecTyKind
Definition Record.h:66
RecTy(RecTyKind K, RecordKeeper &RK)
Definition Record.h:84
virtual std::string getAsString() const =0
void dump() const
Definition Record.cpp:134
const ListRecTy * getListTy() const
Returns the type representing list<thistype>.
Definition Record.cpp:137
const Record * getClass(StringRef Name) const
Get the class with the specified name.
Definition Record.h:2015
const RecordMap & getClasses() const
Get the map of classes.
Definition Record.h:2006
const Init * getNewAnonymousName()
GetNewAnonymousName - Generate a unique anonymous name that can be used as an identifier.
Definition Record.cpp:3304
const RecordMap & getDefs() const
Get the map of records (defs).
Definition Record.h:2009
void dump() const
Definition Record.cpp:3288
detail::RecordKeeperImpl & getImpl()
Return the internal implementation of the RecordKeeper.
Definition Record.h:2000
void dumpAllocationStats(raw_ostream &OS) const
Definition Record.cpp:3348
ArrayRef< const Record * > getAllDerivedDefinitionsIfDefined(StringRef ClassName) const
Get all the concrete records that inherit from specified class, if the class is defined.
Definition Record.cpp:3342
const Record * getDef(StringRef Name) const
Get the concrete record with the specified name.
Definition Record.h:2021
ArrayRef< const Record * > getAllDerivedDefinitions(StringRef ClassName) const
Get all the concrete records that inherit from the one specified class.
Definition Record.cpp:3309
'[classname]' - Type of record values that have zero or more superclasses.
Definition Record.h:235
bool typeIsConvertibleTo(const RecTy *RHS) const override
Return true if all values of 'this' type can be converted to the specified type.
Definition Record.cpp:307
bool isSubClassOf(const Record *Class) const
Definition Record.cpp:301
ArrayRef< const Record * > getClasses() const
Definition Record.h:262
void Profile(FoldingSetNodeID &ID) const
Definition Record.cpp:283
friend class Record
Definition Record.h:237
std::string getAsString() const override
Definition Record.cpp:287
bool typeIsA(const RecTy *RHS) const override
Return true if 'this' type is equal to or a subtype of RHS.
Definition Record.cpp:320
static const RecordRecTy * get(RecordKeeper &RK, ArrayRef< const Record * > Classes)
Get the record type with the given non-redundant list of superclasses.
Definition Record.cpp:241
Resolve all variables from a record except for unset variables.
Definition Record.h:2267
const Init * resolve(const Init *VarName) override
Return the initializer for the given variable name (should normally be a StringInit),...
Definition Record.cpp:3370
This class represents a field in a record, including its name, type, value, and source location.
Definition Record.h:1555
std::string getNameInitAsString() const
Get the name of the field as a std::string.
Definition Record.h:1589
bool isNonconcreteOK() const
Is this a field where nonconcrete values are okay?
Definition Record.h:1597
bool setValue(const Init *V)
Set the value of the field from an Init.
Definition Record.cpp:2892
SMLoc getLoc() const
Get the source location of the point where the field was defined.
Definition Record.h:1594
const Init * getValue() const
Get the value of the field as an Init.
Definition Record.h:1613
bool isUsed() const
Definition Record.h:1630
void dump() const
Definition Record.cpp:2925
StringRef getName() const
Get the name of the field as a StringRef.
Definition Record.cpp:2873
void print(raw_ostream &OS, bool PrintSem=true) const
Print the value to an output stream, possibly with a semicolon.
Definition Record.cpp:2928
RecordVal(const Init *N, const RecTy *T, FieldKind K)
Definition Record.cpp:2859
const Init * getNameInit() const
Get the name of the field as an Init.
Definition Record.h:1586
std::string getPrintType() const
Get the type of the field for printing purposes.
Definition Record.cpp:2877
const RecTy * getType() const
Get the type of the field value as a RecTy.
Definition Record.h:1607
std::vector< int64_t > getValueAsListOfInts(StringRef FieldName) const
This method looks up the specified field and returns its value as a vector of integers,...
Definition Record.cpp:3160
const RecordRecTy * getType() const
Definition Record.cpp:2954
const Init * getValueInit(StringRef FieldName) const
Return the initializer for a value with the specified name, or throw an exception if the field does n...
Definition Record.cpp:3086
bool getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const
This method looks up the specified field and returns its value as a bit.
Definition Record.cpp:3217
bool getValueAsBit(StringRef FieldName) const
This method looks up the specified field and returns its value as a bit, throwing an exception if the...
Definition Record.cpp:3209
@ RK_AnonymousDef
Definition Record.h:1665
static unsigned getNewUID(RecordKeeper &RK)
Definition Record.cpp:2968
ArrayRef< SMLoc > getLoc() const
Definition Record.h:1734
void checkUnusedTemplateArgs()
Definition Record.cpp:3272
void emitRecordDumps()
Definition Record.cpp:3261
ArrayRef< DumpInfo > getDumps() const
Definition Record.h:1767
std::vector< const Record * > getValueAsListOfDefs(StringRef FieldName) const
This method looks up the specified field and returns its value as a vector of records,...
Definition Record.cpp:3135
ArrayRef< AssertionInfo > getAssertions() const
Definition Record.h:1766
std::string getNameInitAsString() const
Definition Record.h:1728
void dump() const
Definition Record.cpp:3040
const Record * getValueAsDef(StringRef FieldName) const
This method looks up the specified field and returns its value as a Record, throwing an exception if ...
Definition Record.cpp:3191
const DagInit * getValueAsDag(StringRef FieldName) const
This method looks up the specified field and returns its value as an Dag, throwing an exception if th...
Definition Record.cpp:3230
std::vector< StringRef > getValueAsListOfStrings(StringRef FieldName) const
This method looks up the specified field and returns its value as a vector of strings,...
Definition Record.cpp:3176
const RecordVal * getValue(const Init *Name) const
Definition Record.h:1798
void addValue(const RecordVal &RV)
Definition Record.h:1823
const Record * getValueAsOptionalDef(StringRef FieldName) const
This method looks up the specified field and returns its value as a Record, returning null if the fie...
Definition Record.cpp:3199
ArrayRef< std::pair< const Record *, SMRange > > getDirectSuperClasses() const
Return the direct superclasses of this record.
Definition Record.h:1790
StringRef getName() const
Definition Record.h:1724
Record(const Init *N, ArrayRef< SMLoc > locs, RecordKeeper &records, RecordKind Kind=RK_Def)
Definition Record.h:1699
void setName(const Init *Name)
Definition Record.cpp:2972
const ListInit * getValueAsListInit(StringRef FieldName) const
This method looks up the specified field and returns its value as a ListInit, throwing an exception i...
Definition Record.cpp:3126
void appendDumps(const Record *Rec)
Definition Record.h:1852
bool isSubClassOf(const Record *R) const
Definition Record.h:1858
DefInit * getDefInit() const
get the corresponding DefInit.
Definition Record.cpp:2960
SMLoc getFieldLoc(StringRef FieldName) const
Return the source location for the named field.
Definition Record.cpp:3078
void resolveReferences(const Init *NewName=nullptr)
If there are any field references that refer to fields that have been filled in, we can propagate the...
Definition Record.cpp:3032
std::optional< StringRef > getValueAsOptionalString(StringRef FieldName) const
This method looks up the specified field and returns its value as a string, throwing an exception if ...
Definition Record.cpp:3103
void removeValue(const Init *Name)
Definition Record.h:1828
ArrayRef< const Init * > getTemplateArgs() const
Definition Record.h:1762
void updateClassLoc(SMLoc Loc)
Definition Record.cpp:2938
const BitsInit * getValueAsBitsInit(StringRef FieldName) const
This method looks up the specified field and returns its value as a BitsInit, throwing an exception i...
Definition Record.cpp:3118
void addDirectSuperClass(const Record *R, SMRange Range)
Definition Record.h:1880
void appendAssertions(const Record *Rec)
Definition Record.h:1848
const Init * getNameInit() const
Definition Record.h:1726
int64_t getValueAsInt(StringRef FieldName) const
This method looks up the specified field and returns its value as an int64_t, throwing an exception i...
Definition Record.cpp:3149
void checkRecordAssertions()
Definition Record.cpp:3242
StringRef getValueAsString(StringRef FieldName) const
This method looks up the specified field and returns its value as a string, throwing an exception if ...
Definition Record.cpp:3094
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition Record.h:2213
const Record * getCurrentRecord() const
Definition Record.h:2221
Represents a location in source code.
Definition SMLoc.h:22
Delegate resolving to a sub-resolver, but shadow some variable names.
Definition Record.h:2283
void addShadow(const Init *Key)
Definition Record.h:2293
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
"foo" - Represent an initialization by a string value.
Definition Record.h:697
static const StringInit * get(RecordKeeper &RK, StringRef, StringFormat Fmt=SF_String)
Definition Record.cpp:678
StringFormat getFormat() const
Definition Record.h:727
StringRef getValue() const
Definition Record.h:726
static StringFormat determineFormat(StringFormat Fmt1, StringFormat Fmt2)
Definition Record.h:722
const Init * convertInitializerTo(const RecTy *Ty) const override
Convert to a value whose type is Ty, or return null if this is not possible.
Definition Record.cpp:689
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&...Args)
Emplace a new element for the specified key into the map if the key isn't already in the map.
Definition StringMap.h:370
'string' - Represent an string value
Definition Record.h:171
std::string getAsString() const override
Definition Record.cpp:196
static const StringRecTy * get(RecordKeeper &RK)
Definition Record.cpp:192
bool typeIsConvertibleTo(const RecTy *RHS) const override
Return true if all values of 'this' type can be converted to the specified type.
Definition Record.cpp:200
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
const Init * Fold(const Record *CurRec) const
Definition Record.cpp:1777
static const TernOpInit * get(TernaryOp opc, const Init *lhs, const Init *mhs, const Init *rhs, const RecTy *Type)
Definition Record.cpp:1631
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2013
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:1983
TernaryOp getOpcode() const
Definition Record.h:1000
(Optionally) delegate resolving to a sub-resolver, and keep track whether there were unresolved refer...
Definition Record.h:2304
const Init * resolve(const Init *VarName) override
Return the initializer for the given variable name (should normally be a StringInit),...
Definition Record.cpp:3395
TrackUnresolvedResolver(Resolver *R=nullptr)
Definition Record.h:2309
See the file comment for details on the usage of the TrailingObjects type.
static constexpr std::enable_if_t< std::is_same_v< Foo< TrailingTys... >, Foo< Tys... > >, size_t > totalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType< TrailingTys, size_t >::type... Counts)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
This is the common superclass of types that have a specific, explicit type, stored in ValueTy.
Definition Record.h:419
const RecTy * getFieldType(const StringInit *FieldName) const override
This method is used to implement the FieldInit class.
Definition Record.cpp:2313
TypedInit(InitKind K, const RecTy *T, uint8_t Opc=0)
Definition Record.h:423
const Init * convertInitializerBitRange(ArrayRef< unsigned > Bits) const override
This function is used to implement the bit range selection operator.
Definition Record.cpp:2335
RecordKeeper & getRecordKeeper() const
Get the record keeper that initialized this Init.
Definition Record.h:439
const Init * getCastTo(const RecTy *Ty) const override
If this value is convertible to type Ty, return a value whose type is Ty, generating a !...
Definition Record.cpp:2351
const Init * convertInitializerTo(const RecTy *Ty) const override
Convert to a value whose type is Ty, or return null if this is not possible.
Definition Record.cpp:2323
const RecTy * getType() const
Get the type of the Init as a RecTy.
Definition Record.h:436
UnaryOp getOpcode() const
Definition Record.h:873
static const UnOpInit * get(UnaryOp opc, const Init *lhs, const RecTy *Type)
Definition Record.cpp:798
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:1011
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:1020
const Init * Fold(const Record *CurRec, bool IsFinal=false) const
Definition Record.cpp:809
A uniquing set that compares nodes against a typed key rather than a serialized FoldingSetNodeID.
Definition FoldingSet.h:709
T * lookup(const KeyTy &Key, FoldingSetInsertToken &Token)
Look up Key.
Definition FoldingSet.h:732
void insert(T *N, FoldingSetInsertToken Token)
Insert N, which must key identically to the lookup that produced Token.
Definition FoldingSet.h:740
'?' - Represents an uninitialized value.
Definition Record.h:454
const Init * getCastTo(const RecTy *Ty) const override
If this value is convertible to type Ty, return a value whose type is Ty, generating a !...
Definition Record.cpp:392
const Init * convertInitializerTo(const RecTy *Ty) const override
Convert to a value whose type is Ty, or return null if this is not possible.
Definition Record.cpp:394
static UnsetInit * get(RecordKeeper &RK)
Get the singleton unset Init.
Definition Record.cpp:388
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
Opcode{0} - Represent access to one bit of a variable or field.
Definition Record.h:1271
static const VarBitInit * get(const TypedInit *T, unsigned B)
Definition Record.cpp:2398
unsigned getBitNum() const
Definition Record.h:1296
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2406
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:2410
size_t args_size() const
Definition Record.h:1381
ArrayRef< const ArgumentInit * > args() const
Definition Record.h:1384
static const VarDefInit * get(SMLoc Loc, const Record *Class, ArrayRef< const ArgumentInit * > Args)
Definition Record.cpp:2452
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:2527
const Init * Fold() const
Definition Record.cpp:2548
void Profile(FoldingSetNodeID &ID) const
Definition Record.cpp:2469
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2561
'Opcode' - Represent a reference to an entire variable object.
Definition Record.h:1234
static const VarInit * get(StringRef VN, const RecTy *T)
Definition Record.cpp:2368
const Init * getBit(unsigned Bit) const override
Get the Init value of the specified bit.
Definition Record.cpp:2386
StringRef getName() const
Definition Record.cpp:2381
const Init * getNameInit() const
Definition Record.h:1252
const Init * resolveReferences(Resolver &R) const override
This method is used by classes that refer to other variables which may not be defined at the time the...
Definition Record.cpp:2392
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
Changed
#define INT64_MIN
Definition DataTypes.h:74
#define INT64_MAX
Definition DataTypes.h:71
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
llvm::SmallVector< std::shared_ptr< RecordsSlice >, 4 > Records
This is an optimization pass for GlobalISel generic memory operations.
@ Length
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:830
void stable_sort(R &&Range)
Definition STLExtras.h:2116
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:840
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI void PrintFatalError(const Twine &Msg)
Definition Error.cpp:132
LLVM_ABI void PrintError(const Twine &Msg)
Definition Error.cpp:104
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
std::string utostr(uint64_t X, bool isNeg=false)
auto uninitialized_copy(R &&Src, IterTy Dst)
Definition STLExtras.h:2111
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
LLVM_ABI bool CheckAssert(SMLoc Loc, const Init *Condition, const Init *Message)
Definition Error.cpp:163
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI void PrintWarning(const Twine &Msg)
Definition Error.cpp:90
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1399
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Sub
Subtraction of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition STLExtras.h:1409
LLVM_ABI void dumpMessage(SMLoc Loc, const Init *Message)
Definition Error.cpp:181
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1772
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
const RecTy * resolveTypes(const RecTy *T1, const RecTy *T2)
Find a common type that T1 and T2 convert to.
Definition Record.cpp:341
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:390
std::variant< unsigned, const Init * > ArgAuxType
Definition Record.h:491
std::string itostr(int64_t X)
FoldingSetImpl< T, Trait > FoldingSet
This template class is used to instantiate a specialized implementation of the folding set to the nod...
Definition FoldingSet.h:525
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#define N
This class represents the internal implementation of the RecordKeeper.
Definition Record.cpp:53
StringMap< const StringInit *, BumpPtrAllocator & > StringInitCodePool
Definition Record.cpp:77
StringRecTy SharedStringRecTy
Definition Record.cpp:65
FoldingSet< BitsInit > TheBitsInitPool
Definition Record.cpp:74
BumpPtrAllocator Allocator
Definition Record.cpp:61
std::map< int64_t, IntInit * > TheIntInitPool
Definition Record.cpp:75
FoldingSet< ArgumentInit > TheArgumentInitPool
Definition Record.cpp:73
UniquingSet< UnOpInit > TheUnOpInitPool
Definition Record.cpp:79
RecordRecTy AnyRecord
Definition Record.cpp:68
DenseMap< std::pair< const Init *, const StringInit * >, FieldInit * > TheFieldInitPool
Definition Record.cpp:91
std::vector< BitsRecTy * > SharedBitsRecTys
Definition Record.cpp:62
UniquingSet< ListInit > TheListInitPool
Definition Record.cpp:78
FoldingSet< RecordRecTy > RecordTypePool
Definition Record.cpp:94
FoldingSet< VarDefInit > TheVarDefInitPool
Definition Record.cpp:89
RecordKeeperImpl(RecordKeeper &RK)
Definition Record.cpp:54
StringMap< const StringInit *, BumpPtrAllocator & > StringInitStringPool
Definition Record.cpp:76
UniquingSet< TernOpInit > TheTernOpInitPool
Definition Record.cpp:81
UniquingSet< BinOpInit > TheBinOpInitPool
Definition Record.cpp:80
FoldingSet< InstancesOpInit > TheInstancesOpInitPool
Definition Record.cpp:85
void dumpAllocationStats(raw_ostream &OS) const
Definition Record.cpp:102
FoldingSet< ExistsOpInit > TheExistsOpInitPool
Definition Record.cpp:84
DenseMap< std::pair< const RecTy *, const Init * >, VarInit * > TheVarInitPool
Definition Record.cpp:86
FoldingSet< IsAOpInit > TheIsAOpInitPool
Definition Record.cpp:83
FoldingSet< DagInit > TheDagInitPool
Definition Record.cpp:93
DenseMap< std::pair< const TypedInit *, unsigned >, VarBitInit * > TheVarBitInitPool
Definition Record.cpp:88
FoldingSet< CondOpInit > TheCondOpInitPool
Definition Record.cpp:92
FoldingSet< FoldOpInit > TheFoldOpInitPool
Definition Record.cpp:82
Sorting predicate to sort record pointers by name.
Definition Record.h:2103