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