Path: blob/main/contrib/llvm-project/llvm/lib/TableGen/Record.cpp
35233 views
//===- Record.cpp - Record implementation ---------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// Implement the tablegen record classes.9//10//===----------------------------------------------------------------------===//1112#include "llvm/TableGen/Record.h"13#include "llvm/ADT/ArrayRef.h"14#include "llvm/ADT/DenseMap.h"15#include "llvm/ADT/FoldingSet.h"16#include "llvm/ADT/SmallString.h"17#include "llvm/ADT/SmallVector.h"18#include "llvm/ADT/StringExtras.h"19#include "llvm/ADT/StringMap.h"20#include "llvm/ADT/StringRef.h"21#include "llvm/Config/llvm-config.h"22#include "llvm/Support/Allocator.h"23#include "llvm/Support/Casting.h"24#include "llvm/Support/Compiler.h"25#include "llvm/Support/ErrorHandling.h"26#include "llvm/Support/MathExtras.h"27#include "llvm/Support/SMLoc.h"28#include "llvm/Support/raw_ostream.h"29#include "llvm/TableGen/Error.h"30#include <cassert>31#include <cstdint>32#include <map>33#include <memory>34#include <string>35#include <utility>36#include <vector>3738using namespace llvm;3940#define DEBUG_TYPE "tblgen-records"4142//===----------------------------------------------------------------------===//43// Context44//===----------------------------------------------------------------------===//4546namespace llvm {47namespace detail {48/// This class represents the internal implementation of the RecordKeeper.49/// It contains all of the contextual static state of the Record classes. It is50/// kept out-of-line to simplify dependencies, and also make it easier for51/// internal classes to access the uniquer state of the keeper.52struct RecordKeeperImpl {53RecordKeeperImpl(RecordKeeper &RK)54: SharedBitRecTy(RK), SharedIntRecTy(RK), SharedStringRecTy(RK),55SharedDagRecTy(RK), AnyRecord(RK, 0), TheUnsetInit(RK),56TrueBitInit(true, &SharedBitRecTy),57FalseBitInit(false, &SharedBitRecTy), StringInitStringPool(Allocator),58StringInitCodePool(Allocator), AnonCounter(0), LastRecordID(0) {}5960BumpPtrAllocator Allocator;61std::vector<BitsRecTy *> SharedBitsRecTys;62BitRecTy SharedBitRecTy;63IntRecTy SharedIntRecTy;64StringRecTy SharedStringRecTy;65DagRecTy SharedDagRecTy;6667RecordRecTy AnyRecord;68UnsetInit TheUnsetInit;69BitInit TrueBitInit;70BitInit FalseBitInit;7172FoldingSet<ArgumentInit> TheArgumentInitPool;73FoldingSet<BitsInit> TheBitsInitPool;74std::map<int64_t, IntInit *> TheIntInitPool;75StringMap<StringInit *, BumpPtrAllocator &> StringInitStringPool;76StringMap<StringInit *, BumpPtrAllocator &> StringInitCodePool;77FoldingSet<ListInit> TheListInitPool;78FoldingSet<UnOpInit> TheUnOpInitPool;79FoldingSet<BinOpInit> TheBinOpInitPool;80FoldingSet<TernOpInit> TheTernOpInitPool;81FoldingSet<FoldOpInit> TheFoldOpInitPool;82FoldingSet<IsAOpInit> TheIsAOpInitPool;83FoldingSet<ExistsOpInit> TheExistsOpInitPool;84DenseMap<std::pair<RecTy *, Init *>, VarInit *> TheVarInitPool;85DenseMap<std::pair<TypedInit *, unsigned>, VarBitInit *> TheVarBitInitPool;86FoldingSet<VarDefInit> TheVarDefInitPool;87DenseMap<std::pair<Init *, StringInit *>, FieldInit *> TheFieldInitPool;88FoldingSet<CondOpInit> TheCondOpInitPool;89FoldingSet<DagInit> TheDagInitPool;90FoldingSet<RecordRecTy> RecordTypePool;9192unsigned AnonCounter;93unsigned LastRecordID;94};95} // namespace detail96} // namespace llvm9798//===----------------------------------------------------------------------===//99// Type implementations100//===----------------------------------------------------------------------===//101102#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)103LLVM_DUMP_METHOD void RecTy::dump() const { print(errs()); }104#endif105106ListRecTy *RecTy::getListTy() {107if (!ListTy)108ListTy = new (RK.getImpl().Allocator) ListRecTy(this);109return ListTy;110}111112bool RecTy::typeIsConvertibleTo(const RecTy *RHS) const {113assert(RHS && "NULL pointer");114return Kind == RHS->getRecTyKind();115}116117bool RecTy::typeIsA(const RecTy *RHS) const { return this == RHS; }118119BitRecTy *BitRecTy::get(RecordKeeper &RK) {120return &RK.getImpl().SharedBitRecTy;121}122123bool BitRecTy::typeIsConvertibleTo(const RecTy *RHS) const{124if (RecTy::typeIsConvertibleTo(RHS) || RHS->getRecTyKind() == IntRecTyKind)125return true;126if (const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))127return BitsTy->getNumBits() == 1;128return false;129}130131BitsRecTy *BitsRecTy::get(RecordKeeper &RK, unsigned Sz) {132detail::RecordKeeperImpl &RKImpl = RK.getImpl();133if (Sz >= RKImpl.SharedBitsRecTys.size())134RKImpl.SharedBitsRecTys.resize(Sz + 1);135BitsRecTy *&Ty = RKImpl.SharedBitsRecTys[Sz];136if (!Ty)137Ty = new (RKImpl.Allocator) BitsRecTy(RK, Sz);138return Ty;139}140141std::string BitsRecTy::getAsString() const {142return "bits<" + utostr(Size) + ">";143}144145bool BitsRecTy::typeIsConvertibleTo(const RecTy *RHS) const {146if (RecTy::typeIsConvertibleTo(RHS)) //argument and the sender are same type147return cast<BitsRecTy>(RHS)->Size == Size;148RecTyKind kind = RHS->getRecTyKind();149return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);150}151152IntRecTy *IntRecTy::get(RecordKeeper &RK) {153return &RK.getImpl().SharedIntRecTy;154}155156bool IntRecTy::typeIsConvertibleTo(const RecTy *RHS) const {157RecTyKind kind = RHS->getRecTyKind();158return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;159}160161StringRecTy *StringRecTy::get(RecordKeeper &RK) {162return &RK.getImpl().SharedStringRecTy;163}164165std::string StringRecTy::getAsString() const {166return "string";167}168169bool StringRecTy::typeIsConvertibleTo(const RecTy *RHS) const {170RecTyKind Kind = RHS->getRecTyKind();171return Kind == StringRecTyKind;172}173174std::string ListRecTy::getAsString() const {175return "list<" + ElementTy->getAsString() + ">";176}177178bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const {179if (const auto *ListTy = dyn_cast<ListRecTy>(RHS))180return ElementTy->typeIsConvertibleTo(ListTy->getElementType());181return false;182}183184bool ListRecTy::typeIsA(const RecTy *RHS) const {185if (const ListRecTy *RHSl = dyn_cast<ListRecTy>(RHS))186return getElementType()->typeIsA(RHSl->getElementType());187return false;188}189190DagRecTy *DagRecTy::get(RecordKeeper &RK) {191return &RK.getImpl().SharedDagRecTy;192}193194std::string DagRecTy::getAsString() const {195return "dag";196}197198static void ProfileRecordRecTy(FoldingSetNodeID &ID,199ArrayRef<Record *> Classes) {200ID.AddInteger(Classes.size());201for (Record *R : Classes)202ID.AddPointer(R);203}204205RecordRecTy *RecordRecTy::get(RecordKeeper &RK,206ArrayRef<Record *> UnsortedClasses) {207detail::RecordKeeperImpl &RKImpl = RK.getImpl();208if (UnsortedClasses.empty())209return &RKImpl.AnyRecord;210211FoldingSet<RecordRecTy> &ThePool = RKImpl.RecordTypePool;212213SmallVector<Record *, 4> Classes(UnsortedClasses.begin(),214UnsortedClasses.end());215llvm::sort(Classes, [](Record *LHS, Record *RHS) {216return LHS->getNameInitAsString() < RHS->getNameInitAsString();217});218219FoldingSetNodeID ID;220ProfileRecordRecTy(ID, Classes);221222void *IP = nullptr;223if (RecordRecTy *Ty = ThePool.FindNodeOrInsertPos(ID, IP))224return Ty;225226#ifndef NDEBUG227// Check for redundancy.228for (unsigned i = 0; i < Classes.size(); ++i) {229for (unsigned j = 0; j < Classes.size(); ++j) {230assert(i == j || !Classes[i]->isSubClassOf(Classes[j]));231}232assert(&Classes[0]->getRecords() == &Classes[i]->getRecords());233}234#endif235236void *Mem = RKImpl.Allocator.Allocate(237totalSizeToAlloc<Record *>(Classes.size()), alignof(RecordRecTy));238RecordRecTy *Ty = new (Mem) RecordRecTy(RK, Classes.size());239std::uninitialized_copy(Classes.begin(), Classes.end(),240Ty->getTrailingObjects<Record *>());241ThePool.InsertNode(Ty, IP);242return Ty;243}244RecordRecTy *RecordRecTy::get(Record *Class) {245assert(Class && "unexpected null class");246return get(Class->getRecords(), Class);247}248249void RecordRecTy::Profile(FoldingSetNodeID &ID) const {250ProfileRecordRecTy(ID, getClasses());251}252253std::string RecordRecTy::getAsString() const {254if (NumClasses == 1)255return getClasses()[0]->getNameInitAsString();256257std::string Str = "{";258bool First = true;259for (Record *R : getClasses()) {260if (!First)261Str += ", ";262First = false;263Str += R->getNameInitAsString();264}265Str += "}";266return Str;267}268269bool RecordRecTy::isSubClassOf(Record *Class) const {270return llvm::any_of(getClasses(), [Class](Record *MySuperClass) {271return MySuperClass == Class ||272MySuperClass->isSubClassOf(Class);273});274}275276bool RecordRecTy::typeIsConvertibleTo(const RecTy *RHS) const {277if (this == RHS)278return true;279280const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);281if (!RTy)282return false;283284return llvm::all_of(RTy->getClasses(), [this](Record *TargetClass) {285return isSubClassOf(TargetClass);286});287}288289bool RecordRecTy::typeIsA(const RecTy *RHS) const {290return typeIsConvertibleTo(RHS);291}292293static RecordRecTy *resolveRecordTypes(RecordRecTy *T1, RecordRecTy *T2) {294SmallVector<Record *, 4> CommonSuperClasses;295SmallVector<Record *, 4> Stack(T1->classes_begin(), T1->classes_end());296297while (!Stack.empty()) {298Record *R = Stack.pop_back_val();299300if (T2->isSubClassOf(R)) {301CommonSuperClasses.push_back(R);302} else {303R->getDirectSuperClasses(Stack);304}305}306307return RecordRecTy::get(T1->getRecordKeeper(), CommonSuperClasses);308}309310RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {311if (T1 == T2)312return T1;313314if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {315if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2))316return resolveRecordTypes(RecTy1, RecTy2);317}318319assert(T1 != nullptr && "Invalid record type");320if (T1->typeIsConvertibleTo(T2))321return T2;322323assert(T2 != nullptr && "Invalid record type");324if (T2->typeIsConvertibleTo(T1))325return T1;326327if (ListRecTy *ListTy1 = dyn_cast<ListRecTy>(T1)) {328if (ListRecTy *ListTy2 = dyn_cast<ListRecTy>(T2)) {329RecTy* NewType = resolveTypes(ListTy1->getElementType(),330ListTy2->getElementType());331if (NewType)332return NewType->getListTy();333}334}335336return nullptr;337}338339//===----------------------------------------------------------------------===//340// Initializer implementations341//===----------------------------------------------------------------------===//342343void Init::anchor() {}344345#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)346LLVM_DUMP_METHOD void Init::dump() const { return print(errs()); }347#endif348349RecordKeeper &Init::getRecordKeeper() const {350if (auto *TyInit = dyn_cast<TypedInit>(this))351return TyInit->getType()->getRecordKeeper();352if (auto *ArgInit = dyn_cast<ArgumentInit>(this))353return ArgInit->getRecordKeeper();354return cast<UnsetInit>(this)->getRecordKeeper();355}356357UnsetInit *UnsetInit::get(RecordKeeper &RK) {358return &RK.getImpl().TheUnsetInit;359}360361Init *UnsetInit::getCastTo(RecTy *Ty) const {362return const_cast<UnsetInit *>(this);363}364365Init *UnsetInit::convertInitializerTo(RecTy *Ty) const {366return const_cast<UnsetInit *>(this);367}368369static void ProfileArgumentInit(FoldingSetNodeID &ID, Init *Value,370ArgAuxType Aux) {371auto I = Aux.index();372ID.AddInteger(I);373if (I == ArgumentInit::Positional)374ID.AddInteger(std::get<ArgumentInit::Positional>(Aux));375if (I == ArgumentInit::Named)376ID.AddPointer(std::get<ArgumentInit::Named>(Aux));377ID.AddPointer(Value);378}379380void ArgumentInit::Profile(FoldingSetNodeID &ID) const {381ProfileArgumentInit(ID, Value, Aux);382}383384ArgumentInit *ArgumentInit::get(Init *Value, ArgAuxType Aux) {385FoldingSetNodeID ID;386ProfileArgumentInit(ID, Value, Aux);387388RecordKeeper &RK = Value->getRecordKeeper();389detail::RecordKeeperImpl &RKImpl = RK.getImpl();390void *IP = nullptr;391if (ArgumentInit *I = RKImpl.TheArgumentInitPool.FindNodeOrInsertPos(ID, IP))392return I;393394ArgumentInit *I = new (RKImpl.Allocator) ArgumentInit(Value, Aux);395RKImpl.TheArgumentInitPool.InsertNode(I, IP);396return I;397}398399Init *ArgumentInit::resolveReferences(Resolver &R) const {400Init *NewValue = Value->resolveReferences(R);401if (NewValue != Value)402return cloneWithValue(NewValue);403404return const_cast<ArgumentInit *>(this);405}406407BitInit *BitInit::get(RecordKeeper &RK, bool V) {408return V ? &RK.getImpl().TrueBitInit : &RK.getImpl().FalseBitInit;409}410411Init *BitInit::convertInitializerTo(RecTy *Ty) const {412if (isa<BitRecTy>(Ty))413return const_cast<BitInit *>(this);414415if (isa<IntRecTy>(Ty))416return IntInit::get(getRecordKeeper(), getValue());417418if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {419// Can only convert single bit.420if (BRT->getNumBits() == 1)421return BitsInit::get(getRecordKeeper(), const_cast<BitInit *>(this));422}423424return nullptr;425}426427static void428ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {429ID.AddInteger(Range.size());430431for (Init *I : Range)432ID.AddPointer(I);433}434435BitsInit *BitsInit::get(RecordKeeper &RK, ArrayRef<Init *> Range) {436FoldingSetNodeID ID;437ProfileBitsInit(ID, Range);438439detail::RecordKeeperImpl &RKImpl = RK.getImpl();440void *IP = nullptr;441if (BitsInit *I = RKImpl.TheBitsInitPool.FindNodeOrInsertPos(ID, IP))442return I;443444void *Mem = RKImpl.Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),445alignof(BitsInit));446BitsInit *I = new (Mem) BitsInit(RK, Range.size());447std::uninitialized_copy(Range.begin(), Range.end(),448I->getTrailingObjects<Init *>());449RKImpl.TheBitsInitPool.InsertNode(I, IP);450return I;451}452453void BitsInit::Profile(FoldingSetNodeID &ID) const {454ProfileBitsInit(ID, ArrayRef(getTrailingObjects<Init *>(), NumBits));455}456457Init *BitsInit::convertInitializerTo(RecTy *Ty) const {458if (isa<BitRecTy>(Ty)) {459if (getNumBits() != 1) return nullptr; // Only accept if just one bit!460return getBit(0);461}462463if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {464// If the number of bits is right, return it. Otherwise we need to expand465// or truncate.466if (getNumBits() != BRT->getNumBits()) return nullptr;467return const_cast<BitsInit *>(this);468}469470if (isa<IntRecTy>(Ty)) {471int64_t Result = 0;472for (unsigned i = 0, e = getNumBits(); i != e; ++i)473if (auto *Bit = dyn_cast<BitInit>(getBit(i)))474Result |= static_cast<int64_t>(Bit->getValue()) << i;475else476return nullptr;477return IntInit::get(getRecordKeeper(), Result);478}479480return nullptr;481}482483Init *484BitsInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {485SmallVector<Init *, 16> NewBits(Bits.size());486487for (unsigned i = 0, e = Bits.size(); i != e; ++i) {488if (Bits[i] >= getNumBits())489return nullptr;490NewBits[i] = getBit(Bits[i]);491}492return BitsInit::get(getRecordKeeper(), NewBits);493}494495bool BitsInit::isConcrete() const {496for (unsigned i = 0, e = getNumBits(); i != e; ++i) {497if (!getBit(i)->isConcrete())498return false;499}500return true;501}502503std::string BitsInit::getAsString() const {504std::string Result = "{ ";505for (unsigned i = 0, e = getNumBits(); i != e; ++i) {506if (i) Result += ", ";507if (Init *Bit = getBit(e-i-1))508Result += Bit->getAsString();509else510Result += "*";511}512return Result + " }";513}514515// resolveReferences - If there are any field references that refer to fields516// that have been filled in, we can propagate the values now.517Init *BitsInit::resolveReferences(Resolver &R) const {518bool Changed = false;519SmallVector<Init *, 16> NewBits(getNumBits());520521Init *CachedBitVarRef = nullptr;522Init *CachedBitVarResolved = nullptr;523524for (unsigned i = 0, e = getNumBits(); i != e; ++i) {525Init *CurBit = getBit(i);526Init *NewBit = CurBit;527528if (VarBitInit *CurBitVar = dyn_cast<VarBitInit>(CurBit)) {529if (CurBitVar->getBitVar() != CachedBitVarRef) {530CachedBitVarRef = CurBitVar->getBitVar();531CachedBitVarResolved = CachedBitVarRef->resolveReferences(R);532}533assert(CachedBitVarResolved && "Unresolved bitvar reference");534NewBit = CachedBitVarResolved->getBit(CurBitVar->getBitNum());535} else {536// getBit(0) implicitly converts int and bits<1> values to bit.537NewBit = CurBit->resolveReferences(R)->getBit(0);538}539540if (isa<UnsetInit>(NewBit) && R.keepUnsetBits())541NewBit = CurBit;542NewBits[i] = NewBit;543Changed |= CurBit != NewBit;544}545546if (Changed)547return BitsInit::get(getRecordKeeper(), NewBits);548549return const_cast<BitsInit *>(this);550}551552IntInit *IntInit::get(RecordKeeper &RK, int64_t V) {553IntInit *&I = RK.getImpl().TheIntInitPool[V];554if (!I)555I = new (RK.getImpl().Allocator) IntInit(RK, V);556return I;557}558559std::string IntInit::getAsString() const {560return itostr(Value);561}562563static bool canFitInBitfield(int64_t Value, unsigned NumBits) {564// For example, with NumBits == 4, we permit Values from [-7 .. 15].565return (NumBits >= sizeof(Value) * 8) ||566(Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);567}568569Init *IntInit::convertInitializerTo(RecTy *Ty) const {570if (isa<IntRecTy>(Ty))571return const_cast<IntInit *>(this);572573if (isa<BitRecTy>(Ty)) {574int64_t Val = getValue();575if (Val != 0 && Val != 1) return nullptr; // Only accept 0 or 1 for a bit!576return BitInit::get(getRecordKeeper(), Val != 0);577}578579if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {580int64_t Value = getValue();581// Make sure this bitfield is large enough to hold the integer value.582if (!canFitInBitfield(Value, BRT->getNumBits()))583return nullptr;584585SmallVector<Init *, 16> NewBits(BRT->getNumBits());586for (unsigned i = 0; i != BRT->getNumBits(); ++i)587NewBits[i] =588BitInit::get(getRecordKeeper(), Value & ((i < 64) ? (1LL << i) : 0));589590return BitsInit::get(getRecordKeeper(), NewBits);591}592593return nullptr;594}595596Init *597IntInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {598SmallVector<Init *, 16> NewBits(Bits.size());599600for (unsigned i = 0, e = Bits.size(); i != e; ++i) {601if (Bits[i] >= 64)602return nullptr;603604NewBits[i] =605BitInit::get(getRecordKeeper(), Value & (INT64_C(1) << Bits[i]));606}607return BitsInit::get(getRecordKeeper(), NewBits);608}609610AnonymousNameInit *AnonymousNameInit::get(RecordKeeper &RK, unsigned V) {611return new (RK.getImpl().Allocator) AnonymousNameInit(RK, V);612}613614StringInit *AnonymousNameInit::getNameInit() const {615return StringInit::get(getRecordKeeper(), getAsString());616}617618std::string AnonymousNameInit::getAsString() const {619return "anonymous_" + utostr(Value);620}621622Init *AnonymousNameInit::resolveReferences(Resolver &R) const {623auto *Old = const_cast<Init *>(static_cast<const Init *>(this));624auto *New = R.resolve(Old);625New = New ? New : Old;626if (R.isFinal())627if (auto *Anonymous = dyn_cast<AnonymousNameInit>(New))628return Anonymous->getNameInit();629return New;630}631632StringInit *StringInit::get(RecordKeeper &RK, StringRef V, StringFormat Fmt) {633detail::RecordKeeperImpl &RKImpl = RK.getImpl();634auto &InitMap = Fmt == SF_String ? RKImpl.StringInitStringPool635: RKImpl.StringInitCodePool;636auto &Entry = *InitMap.insert(std::make_pair(V, nullptr)).first;637if (!Entry.second)638Entry.second = new (RKImpl.Allocator) StringInit(RK, Entry.getKey(), Fmt);639return Entry.second;640}641642Init *StringInit::convertInitializerTo(RecTy *Ty) const {643if (isa<StringRecTy>(Ty))644return const_cast<StringInit *>(this);645646return nullptr;647}648649static void ProfileListInit(FoldingSetNodeID &ID,650ArrayRef<Init *> Range,651RecTy *EltTy) {652ID.AddInteger(Range.size());653ID.AddPointer(EltTy);654655for (Init *I : Range)656ID.AddPointer(I);657}658659ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {660FoldingSetNodeID ID;661ProfileListInit(ID, Range, EltTy);662663detail::RecordKeeperImpl &RK = EltTy->getRecordKeeper().getImpl();664void *IP = nullptr;665if (ListInit *I = RK.TheListInitPool.FindNodeOrInsertPos(ID, IP))666return I;667668assert(Range.empty() || !isa<TypedInit>(Range[0]) ||669cast<TypedInit>(Range[0])->getType()->typeIsConvertibleTo(EltTy));670671void *Mem = RK.Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),672alignof(ListInit));673ListInit *I = new (Mem) ListInit(Range.size(), EltTy);674std::uninitialized_copy(Range.begin(), Range.end(),675I->getTrailingObjects<Init *>());676RK.TheListInitPool.InsertNode(I, IP);677return I;678}679680void ListInit::Profile(FoldingSetNodeID &ID) const {681RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();682683ProfileListInit(ID, getValues(), EltTy);684}685686Init *ListInit::convertInitializerTo(RecTy *Ty) const {687if (getType() == Ty)688return const_cast<ListInit*>(this);689690if (auto *LRT = dyn_cast<ListRecTy>(Ty)) {691SmallVector<Init*, 8> Elements;692Elements.reserve(getValues().size());693694// Verify that all of the elements of the list are subclasses of the695// appropriate class!696bool Changed = false;697RecTy *ElementType = LRT->getElementType();698for (Init *I : getValues())699if (Init *CI = I->convertInitializerTo(ElementType)) {700Elements.push_back(CI);701if (CI != I)702Changed = true;703} else704return nullptr;705706if (!Changed)707return const_cast<ListInit*>(this);708return ListInit::get(Elements, ElementType);709}710711return nullptr;712}713714Record *ListInit::getElementAsRecord(unsigned i) const {715assert(i < NumValues && "List element index out of range!");716DefInit *DI = dyn_cast<DefInit>(getElement(i));717if (!DI)718PrintFatalError("Expected record in list!");719return DI->getDef();720}721722Init *ListInit::resolveReferences(Resolver &R) const {723SmallVector<Init*, 8> Resolved;724Resolved.reserve(size());725bool Changed = false;726727for (Init *CurElt : getValues()) {728Init *E = CurElt->resolveReferences(R);729Changed |= E != CurElt;730Resolved.push_back(E);731}732733if (Changed)734return ListInit::get(Resolved, getElementType());735return const_cast<ListInit *>(this);736}737738bool ListInit::isComplete() const {739for (Init *Element : *this) {740if (!Element->isComplete())741return false;742}743return true;744}745746bool ListInit::isConcrete() const {747for (Init *Element : *this) {748if (!Element->isConcrete())749return false;750}751return true;752}753754std::string ListInit::getAsString() const {755std::string Result = "[";756const char *sep = "";757for (Init *Element : *this) {758Result += sep;759sep = ", ";760Result += Element->getAsString();761}762return Result + "]";763}764765Init *OpInit::getBit(unsigned Bit) const {766if (getType() == BitRecTy::get(getRecordKeeper()))767return const_cast<OpInit*>(this);768return VarBitInit::get(const_cast<OpInit*>(this), Bit);769}770771static void772ProfileUnOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *Op, RecTy *Type) {773ID.AddInteger(Opcode);774ID.AddPointer(Op);775ID.AddPointer(Type);776}777778UnOpInit *UnOpInit::get(UnaryOp Opc, Init *LHS, RecTy *Type) {779FoldingSetNodeID ID;780ProfileUnOpInit(ID, Opc, LHS, Type);781782detail::RecordKeeperImpl &RK = Type->getRecordKeeper().getImpl();783void *IP = nullptr;784if (UnOpInit *I = RK.TheUnOpInitPool.FindNodeOrInsertPos(ID, IP))785return I;786787UnOpInit *I = new (RK.Allocator) UnOpInit(Opc, LHS, Type);788RK.TheUnOpInitPool.InsertNode(I, IP);789return I;790}791792void UnOpInit::Profile(FoldingSetNodeID &ID) const {793ProfileUnOpInit(ID, getOpcode(), getOperand(), getType());794}795796Init *UnOpInit::Fold(Record *CurRec, bool IsFinal) const {797RecordKeeper &RK = getRecordKeeper();798switch (getOpcode()) {799case REPR:800if (LHS->isConcrete()) {801// If it is a Record, print the full content.802if (const auto *Def = dyn_cast<DefInit>(LHS)) {803std::string S;804raw_string_ostream OS(S);805OS << *Def->getDef();806OS.flush();807return StringInit::get(RK, S);808} else {809// Otherwise, print the value of the variable.810//811// NOTE: we could recursively !repr the elements of a list,812// but that could produce a lot of output when printing a813// defset.814return StringInit::get(RK, LHS->getAsString());815}816}817break;818case TOLOWER:819if (StringInit *LHSs = dyn_cast<StringInit>(LHS))820return StringInit::get(RK, LHSs->getValue().lower());821break;822case TOUPPER:823if (StringInit *LHSs = dyn_cast<StringInit>(LHS))824return StringInit::get(RK, LHSs->getValue().upper());825break;826case CAST:827if (isa<StringRecTy>(getType())) {828if (StringInit *LHSs = dyn_cast<StringInit>(LHS))829return LHSs;830831if (DefInit *LHSd = dyn_cast<DefInit>(LHS))832return StringInit::get(RK, LHSd->getAsString());833834if (IntInit *LHSi = dyn_cast_or_null<IntInit>(835LHS->convertInitializerTo(IntRecTy::get(RK))))836return StringInit::get(RK, LHSi->getAsString());837838} else if (isa<RecordRecTy>(getType())) {839if (StringInit *Name = dyn_cast<StringInit>(LHS)) {840Record *D = RK.getDef(Name->getValue());841if (!D && CurRec) {842// Self-references are allowed, but their resolution is delayed until843// the final resolve to ensure that we get the correct type for them.844auto *Anonymous = dyn_cast<AnonymousNameInit>(CurRec->getNameInit());845if (Name == CurRec->getNameInit() ||846(Anonymous && Name == Anonymous->getNameInit())) {847if (!IsFinal)848break;849D = CurRec;850}851}852853auto PrintFatalErrorHelper = [CurRec](const Twine &T) {854if (CurRec)855PrintFatalError(CurRec->getLoc(), T);856else857PrintFatalError(T);858};859860if (!D) {861if (IsFinal) {862PrintFatalErrorHelper(Twine("Undefined reference to record: '") +863Name->getValue() + "'\n");864}865break;866}867868DefInit *DI = DefInit::get(D);869if (!DI->getType()->typeIsA(getType())) {870PrintFatalErrorHelper(Twine("Expected type '") +871getType()->getAsString() + "', got '" +872DI->getType()->getAsString() + "' in: " +873getAsString() + "\n");874}875return DI;876}877}878879if (Init *NewInit = LHS->convertInitializerTo(getType()))880return NewInit;881break;882883case NOT:884if (IntInit *LHSi = dyn_cast_or_null<IntInit>(885LHS->convertInitializerTo(IntRecTy::get(RK))))886return IntInit::get(RK, LHSi->getValue() ? 0 : 1);887break;888889case HEAD:890if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {891assert(!LHSl->empty() && "Empty list in head");892return LHSl->getElement(0);893}894break;895896case TAIL:897if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {898assert(!LHSl->empty() && "Empty list in tail");899// Note the +1. We can't just pass the result of getValues()900// directly.901return ListInit::get(LHSl->getValues().slice(1), LHSl->getElementType());902}903break;904905case SIZE:906if (ListInit *LHSl = dyn_cast<ListInit>(LHS))907return IntInit::get(RK, LHSl->size());908if (DagInit *LHSd = dyn_cast<DagInit>(LHS))909return IntInit::get(RK, LHSd->arg_size());910if (StringInit *LHSs = dyn_cast<StringInit>(LHS))911return IntInit::get(RK, LHSs->getValue().size());912break;913914case EMPTY:915if (ListInit *LHSl = dyn_cast<ListInit>(LHS))916return IntInit::get(RK, LHSl->empty());917if (DagInit *LHSd = dyn_cast<DagInit>(LHS))918return IntInit::get(RK, LHSd->arg_empty());919if (StringInit *LHSs = dyn_cast<StringInit>(LHS))920return IntInit::get(RK, LHSs->getValue().empty());921break;922923case GETDAGOP:924if (DagInit *Dag = dyn_cast<DagInit>(LHS)) {925// TI is not necessarily a def due to the late resolution in multiclasses,926// but has to be a TypedInit.927auto *TI = cast<TypedInit>(Dag->getOperator());928if (!TI->getType()->typeIsA(getType())) {929PrintFatalError(CurRec->getLoc(),930Twine("Expected type '") + getType()->getAsString() +931"', got '" + TI->getType()->getAsString() +932"' in: " + getAsString() + "\n");933} else {934return Dag->getOperator();935}936}937break;938939case LOG2:940if (IntInit *LHSi = dyn_cast_or_null<IntInit>(941LHS->convertInitializerTo(IntRecTy::get(RK)))) {942int64_t LHSv = LHSi->getValue();943if (LHSv <= 0) {944PrintFatalError(CurRec->getLoc(),945"Illegal operation: logtwo is undefined "946"on arguments less than or equal to 0");947} else {948uint64_t Log = Log2_64(LHSv);949assert(Log <= INT64_MAX &&950"Log of an int64_t must be smaller than INT64_MAX");951return IntInit::get(RK, static_cast<int64_t>(Log));952}953}954break;955}956return const_cast<UnOpInit *>(this);957}958959Init *UnOpInit::resolveReferences(Resolver &R) const {960Init *lhs = LHS->resolveReferences(R);961962if (LHS != lhs || (R.isFinal() && getOpcode() == CAST))963return (UnOpInit::get(getOpcode(), lhs, getType()))964->Fold(R.getCurrentRecord(), R.isFinal());965return const_cast<UnOpInit *>(this);966}967968std::string UnOpInit::getAsString() const {969std::string Result;970switch (getOpcode()) {971case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;972case NOT: Result = "!not"; break;973case HEAD: Result = "!head"; break;974case TAIL: Result = "!tail"; break;975case SIZE: Result = "!size"; break;976case EMPTY: Result = "!empty"; break;977case GETDAGOP: Result = "!getdagop"; break;978case LOG2 : Result = "!logtwo"; break;979case REPR:980Result = "!repr";981break;982case TOLOWER:983Result = "!tolower";984break;985case TOUPPER:986Result = "!toupper";987break;988}989return Result + "(" + LHS->getAsString() + ")";990}991992static void993ProfileBinOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *RHS,994RecTy *Type) {995ID.AddInteger(Opcode);996ID.AddPointer(LHS);997ID.AddPointer(RHS);998ID.AddPointer(Type);999}10001001BinOpInit *BinOpInit::get(BinaryOp Opc, Init *LHS, Init *RHS, RecTy *Type) {1002FoldingSetNodeID ID;1003ProfileBinOpInit(ID, Opc, LHS, RHS, Type);10041005detail::RecordKeeperImpl &RK = LHS->getRecordKeeper().getImpl();1006void *IP = nullptr;1007if (BinOpInit *I = RK.TheBinOpInitPool.FindNodeOrInsertPos(ID, IP))1008return I;10091010BinOpInit *I = new (RK.Allocator) BinOpInit(Opc, LHS, RHS, Type);1011RK.TheBinOpInitPool.InsertNode(I, IP);1012return I;1013}10141015void BinOpInit::Profile(FoldingSetNodeID &ID) const {1016ProfileBinOpInit(ID, getOpcode(), getLHS(), getRHS(), getType());1017}10181019static StringInit *ConcatStringInits(const StringInit *I0,1020const StringInit *I1) {1021SmallString<80> Concat(I0->getValue());1022Concat.append(I1->getValue());1023return StringInit::get(1024I0->getRecordKeeper(), Concat,1025StringInit::determineFormat(I0->getFormat(), I1->getFormat()));1026}10271028static StringInit *interleaveStringList(const ListInit *List,1029const StringInit *Delim) {1030if (List->size() == 0)1031return StringInit::get(List->getRecordKeeper(), "");1032StringInit *Element = dyn_cast<StringInit>(List->getElement(0));1033if (!Element)1034return nullptr;1035SmallString<80> Result(Element->getValue());1036StringInit::StringFormat Fmt = StringInit::SF_String;10371038for (unsigned I = 1, E = List->size(); I < E; ++I) {1039Result.append(Delim->getValue());1040StringInit *Element = dyn_cast<StringInit>(List->getElement(I));1041if (!Element)1042return nullptr;1043Result.append(Element->getValue());1044Fmt = StringInit::determineFormat(Fmt, Element->getFormat());1045}1046return StringInit::get(List->getRecordKeeper(), Result, Fmt);1047}10481049static StringInit *interleaveIntList(const ListInit *List,1050const StringInit *Delim) {1051RecordKeeper &RK = List->getRecordKeeper();1052if (List->size() == 0)1053return StringInit::get(RK, "");1054IntInit *Element = dyn_cast_or_null<IntInit>(1055List->getElement(0)->convertInitializerTo(IntRecTy::get(RK)));1056if (!Element)1057return nullptr;1058SmallString<80> Result(Element->getAsString());10591060for (unsigned I = 1, E = List->size(); I < E; ++I) {1061Result.append(Delim->getValue());1062IntInit *Element = dyn_cast_or_null<IntInit>(1063List->getElement(I)->convertInitializerTo(IntRecTy::get(RK)));1064if (!Element)1065return nullptr;1066Result.append(Element->getAsString());1067}1068return StringInit::get(RK, Result);1069}10701071Init *BinOpInit::getStrConcat(Init *I0, Init *I1) {1072// Shortcut for the common case of concatenating two strings.1073if (const StringInit *I0s = dyn_cast<StringInit>(I0))1074if (const StringInit *I1s = dyn_cast<StringInit>(I1))1075return ConcatStringInits(I0s, I1s);1076return BinOpInit::get(BinOpInit::STRCONCAT, I0, I1,1077StringRecTy::get(I0->getRecordKeeper()));1078}10791080static ListInit *ConcatListInits(const ListInit *LHS,1081const ListInit *RHS) {1082SmallVector<Init *, 8> Args;1083llvm::append_range(Args, *LHS);1084llvm::append_range(Args, *RHS);1085return ListInit::get(Args, LHS->getElementType());1086}10871088Init *BinOpInit::getListConcat(TypedInit *LHS, Init *RHS) {1089assert(isa<ListRecTy>(LHS->getType()) && "First arg must be a list");10901091// Shortcut for the common case of concatenating two lists.1092if (const ListInit *LHSList = dyn_cast<ListInit>(LHS))1093if (const ListInit *RHSList = dyn_cast<ListInit>(RHS))1094return ConcatListInits(LHSList, RHSList);1095return BinOpInit::get(BinOpInit::LISTCONCAT, LHS, RHS, LHS->getType());1096}10971098std::optional<bool> BinOpInit::CompareInit(unsigned Opc, Init *LHS,1099Init *RHS) const {1100// First see if we have two bit, bits, or int.1101IntInit *LHSi = dyn_cast_or_null<IntInit>(1102LHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));1103IntInit *RHSi = dyn_cast_or_null<IntInit>(1104RHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));11051106if (LHSi && RHSi) {1107bool Result;1108switch (Opc) {1109case EQ:1110Result = LHSi->getValue() == RHSi->getValue();1111break;1112case NE:1113Result = LHSi->getValue() != RHSi->getValue();1114break;1115case LE:1116Result = LHSi->getValue() <= RHSi->getValue();1117break;1118case LT:1119Result = LHSi->getValue() < RHSi->getValue();1120break;1121case GE:1122Result = LHSi->getValue() >= RHSi->getValue();1123break;1124case GT:1125Result = LHSi->getValue() > RHSi->getValue();1126break;1127default:1128llvm_unreachable("unhandled comparison");1129}1130return Result;1131}11321133// Next try strings.1134StringInit *LHSs = dyn_cast<StringInit>(LHS);1135StringInit *RHSs = dyn_cast<StringInit>(RHS);11361137if (LHSs && RHSs) {1138bool Result;1139switch (Opc) {1140case EQ:1141Result = LHSs->getValue() == RHSs->getValue();1142break;1143case NE:1144Result = LHSs->getValue() != RHSs->getValue();1145break;1146case LE:1147Result = LHSs->getValue() <= RHSs->getValue();1148break;1149case LT:1150Result = LHSs->getValue() < RHSs->getValue();1151break;1152case GE:1153Result = LHSs->getValue() >= RHSs->getValue();1154break;1155case GT:1156Result = LHSs->getValue() > RHSs->getValue();1157break;1158default:1159llvm_unreachable("unhandled comparison");1160}1161return Result;1162}11631164// Finally, !eq and !ne can be used with records.1165if (Opc == EQ || Opc == NE) {1166DefInit *LHSd = dyn_cast<DefInit>(LHS);1167DefInit *RHSd = dyn_cast<DefInit>(RHS);1168if (LHSd && RHSd)1169return (Opc == EQ) ? LHSd == RHSd : LHSd != RHSd;1170}11711172return std::nullopt;1173}11741175static std::optional<unsigned> getDagArgNoByKey(DagInit *Dag, Init *Key,1176std::string &Error) {1177// Accessor by index1178if (IntInit *Idx = dyn_cast<IntInit>(Key)) {1179int64_t Pos = Idx->getValue();1180if (Pos < 0) {1181// The index is negative.1182Error =1183(Twine("index ") + std::to_string(Pos) + Twine(" is negative")).str();1184return std::nullopt;1185}1186if (Pos >= Dag->getNumArgs()) {1187// The index is out-of-range.1188Error = (Twine("index ") + std::to_string(Pos) +1189" is out of range (dag has " +1190std::to_string(Dag->getNumArgs()) + " arguments)")1191.str();1192return std::nullopt;1193}1194return Pos;1195}1196assert(isa<StringInit>(Key));1197// Accessor by name1198StringInit *Name = dyn_cast<StringInit>(Key);1199auto ArgNo = Dag->getArgNo(Name->getValue());1200if (!ArgNo) {1201// The key is not found.1202Error = (Twine("key '") + Name->getValue() + Twine("' is not found")).str();1203return std::nullopt;1204}1205return *ArgNo;1206}12071208Init *BinOpInit::Fold(Record *CurRec) const {1209switch (getOpcode()) {1210case CONCAT: {1211DagInit *LHSs = dyn_cast<DagInit>(LHS);1212DagInit *RHSs = dyn_cast<DagInit>(RHS);1213if (LHSs && RHSs) {1214DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());1215DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());1216if ((!LOp && !isa<UnsetInit>(LHSs->getOperator())) ||1217(!ROp && !isa<UnsetInit>(RHSs->getOperator())))1218break;1219if (LOp && ROp && LOp->getDef() != ROp->getDef()) {1220PrintFatalError(Twine("Concatenated Dag operators do not match: '") +1221LHSs->getAsString() + "' vs. '" + RHSs->getAsString() +1222"'");1223}1224Init *Op = LOp ? LOp : ROp;1225if (!Op)1226Op = UnsetInit::get(getRecordKeeper());12271228SmallVector<Init*, 8> Args;1229SmallVector<StringInit*, 8> ArgNames;1230for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {1231Args.push_back(LHSs->getArg(i));1232ArgNames.push_back(LHSs->getArgName(i));1233}1234for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {1235Args.push_back(RHSs->getArg(i));1236ArgNames.push_back(RHSs->getArgName(i));1237}1238return DagInit::get(Op, nullptr, Args, ArgNames);1239}1240break;1241}1242case LISTCONCAT: {1243ListInit *LHSs = dyn_cast<ListInit>(LHS);1244ListInit *RHSs = dyn_cast<ListInit>(RHS);1245if (LHSs && RHSs) {1246SmallVector<Init *, 8> Args;1247llvm::append_range(Args, *LHSs);1248llvm::append_range(Args, *RHSs);1249return ListInit::get(Args, LHSs->getElementType());1250}1251break;1252}1253case LISTSPLAT: {1254TypedInit *Value = dyn_cast<TypedInit>(LHS);1255IntInit *Size = dyn_cast<IntInit>(RHS);1256if (Value && Size) {1257SmallVector<Init *, 8> Args(Size->getValue(), Value);1258return ListInit::get(Args, Value->getType());1259}1260break;1261}1262case LISTREMOVE: {1263ListInit *LHSs = dyn_cast<ListInit>(LHS);1264ListInit *RHSs = dyn_cast<ListInit>(RHS);1265if (LHSs && RHSs) {1266SmallVector<Init *, 8> Args;1267for (Init *EltLHS : *LHSs) {1268bool Found = false;1269for (Init *EltRHS : *RHSs) {1270if (std::optional<bool> Result = CompareInit(EQ, EltLHS, EltRHS)) {1271if (*Result) {1272Found = true;1273break;1274}1275}1276}1277if (!Found)1278Args.push_back(EltLHS);1279}1280return ListInit::get(Args, LHSs->getElementType());1281}1282break;1283}1284case LISTELEM: {1285auto *TheList = dyn_cast<ListInit>(LHS);1286auto *Idx = dyn_cast<IntInit>(RHS);1287if (!TheList || !Idx)1288break;1289auto i = Idx->getValue();1290if (i < 0 || i >= (ssize_t)TheList->size())1291break;1292return TheList->getElement(i);1293}1294case LISTSLICE: {1295auto *TheList = dyn_cast<ListInit>(LHS);1296auto *SliceIdxs = dyn_cast<ListInit>(RHS);1297if (!TheList || !SliceIdxs)1298break;1299SmallVector<Init *, 8> Args;1300Args.reserve(SliceIdxs->size());1301for (auto *I : *SliceIdxs) {1302auto *II = dyn_cast<IntInit>(I);1303if (!II)1304goto unresolved;1305auto i = II->getValue();1306if (i < 0 || i >= (ssize_t)TheList->size())1307goto unresolved;1308Args.push_back(TheList->getElement(i));1309}1310return ListInit::get(Args, TheList->getElementType());1311}1312case RANGEC: {1313auto *LHSi = dyn_cast<IntInit>(LHS);1314auto *RHSi = dyn_cast<IntInit>(RHS);1315if (!LHSi || !RHSi)1316break;13171318auto Start = LHSi->getValue();1319auto End = RHSi->getValue();1320SmallVector<Init *, 8> Args;1321if (getOpcode() == RANGEC) {1322// Closed interval1323if (Start <= End) {1324// Ascending order1325Args.reserve(End - Start + 1);1326for (auto i = Start; i <= End; ++i)1327Args.push_back(IntInit::get(getRecordKeeper(), i));1328} else {1329// Descending order1330Args.reserve(Start - End + 1);1331for (auto i = Start; i >= End; --i)1332Args.push_back(IntInit::get(getRecordKeeper(), i));1333}1334} else if (Start < End) {1335// Half-open interval (excludes `End`)1336Args.reserve(End - Start);1337for (auto i = Start; i < End; ++i)1338Args.push_back(IntInit::get(getRecordKeeper(), i));1339} else {1340// Empty set1341}1342return ListInit::get(Args, LHSi->getType());1343}1344case STRCONCAT: {1345StringInit *LHSs = dyn_cast<StringInit>(LHS);1346StringInit *RHSs = dyn_cast<StringInit>(RHS);1347if (LHSs && RHSs)1348return ConcatStringInits(LHSs, RHSs);1349break;1350}1351case INTERLEAVE: {1352ListInit *List = dyn_cast<ListInit>(LHS);1353StringInit *Delim = dyn_cast<StringInit>(RHS);1354if (List && Delim) {1355StringInit *Result;1356if (isa<StringRecTy>(List->getElementType()))1357Result = interleaveStringList(List, Delim);1358else1359Result = interleaveIntList(List, Delim);1360if (Result)1361return Result;1362}1363break;1364}1365case EQ:1366case NE:1367case LE:1368case LT:1369case GE:1370case GT: {1371if (std::optional<bool> Result = CompareInit(getOpcode(), LHS, RHS))1372return BitInit::get(getRecordKeeper(), *Result);1373break;1374}1375case GETDAGARG: {1376DagInit *Dag = dyn_cast<DagInit>(LHS);1377if (Dag && isa<IntInit, StringInit>(RHS)) {1378std::string Error;1379auto ArgNo = getDagArgNoByKey(Dag, RHS, Error);1380if (!ArgNo)1381PrintFatalError(CurRec->getLoc(), "!getdagarg " + Error);13821383assert(*ArgNo < Dag->getNumArgs());13841385Init *Arg = Dag->getArg(*ArgNo);1386if (auto *TI = dyn_cast<TypedInit>(Arg))1387if (!TI->getType()->typeIsConvertibleTo(getType()))1388return UnsetInit::get(Dag->getRecordKeeper());1389return Arg;1390}1391break;1392}1393case GETDAGNAME: {1394DagInit *Dag = dyn_cast<DagInit>(LHS);1395IntInit *Idx = dyn_cast<IntInit>(RHS);1396if (Dag && Idx) {1397int64_t Pos = Idx->getValue();1398if (Pos < 0 || Pos >= Dag->getNumArgs()) {1399// The index is out-of-range.1400PrintError(CurRec->getLoc(),1401Twine("!getdagname index is out of range 0...") +1402std::to_string(Dag->getNumArgs() - 1) + ": " +1403std::to_string(Pos));1404}1405Init *ArgName = Dag->getArgName(Pos);1406if (!ArgName)1407return UnsetInit::get(getRecordKeeper());1408return ArgName;1409}1410break;1411}1412case SETDAGOP: {1413DagInit *Dag = dyn_cast<DagInit>(LHS);1414DefInit *Op = dyn_cast<DefInit>(RHS);1415if (Dag && Op) {1416SmallVector<Init*, 8> Args;1417SmallVector<StringInit*, 8> ArgNames;1418for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {1419Args.push_back(Dag->getArg(i));1420ArgNames.push_back(Dag->getArgName(i));1421}1422return DagInit::get(Op, nullptr, Args, ArgNames);1423}1424break;1425}1426case ADD:1427case SUB:1428case MUL:1429case DIV:1430case AND:1431case OR:1432case XOR:1433case SHL:1434case SRA:1435case SRL: {1436IntInit *LHSi = dyn_cast_or_null<IntInit>(1437LHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));1438IntInit *RHSi = dyn_cast_or_null<IntInit>(1439RHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));1440if (LHSi && RHSi) {1441int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();1442int64_t Result;1443switch (getOpcode()) {1444default: llvm_unreachable("Bad opcode!");1445case ADD: Result = LHSv + RHSv; break;1446case SUB: Result = LHSv - RHSv; break;1447case MUL: Result = LHSv * RHSv; break;1448case DIV:1449if (RHSv == 0)1450PrintFatalError(CurRec->getLoc(),1451"Illegal operation: division by zero");1452else if (LHSv == INT64_MIN && RHSv == -1)1453PrintFatalError(CurRec->getLoc(),1454"Illegal operation: INT64_MIN / -1");1455else1456Result = LHSv / RHSv;1457break;1458case AND: Result = LHSv & RHSv; break;1459case OR: Result = LHSv | RHSv; break;1460case XOR: Result = LHSv ^ RHSv; break;1461case SHL: Result = (uint64_t)LHSv << (uint64_t)RHSv; break;1462case SRA: Result = LHSv >> RHSv; break;1463case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;1464}1465return IntInit::get(getRecordKeeper(), Result);1466}1467break;1468}1469}1470unresolved:1471return const_cast<BinOpInit *>(this);1472}14731474Init *BinOpInit::resolveReferences(Resolver &R) const {1475Init *lhs = LHS->resolveReferences(R);1476Init *rhs = RHS->resolveReferences(R);14771478if (LHS != lhs || RHS != rhs)1479return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))1480->Fold(R.getCurrentRecord());1481return const_cast<BinOpInit *>(this);1482}14831484std::string BinOpInit::getAsString() const {1485std::string Result;1486switch (getOpcode()) {1487case LISTELEM:1488case LISTSLICE:1489return LHS->getAsString() + "[" + RHS->getAsString() + "]";1490case RANGEC:1491return LHS->getAsString() + "..." + RHS->getAsString();1492case CONCAT: Result = "!con"; break;1493case ADD: Result = "!add"; break;1494case SUB: Result = "!sub"; break;1495case MUL: Result = "!mul"; break;1496case DIV: Result = "!div"; break;1497case AND: Result = "!and"; break;1498case OR: Result = "!or"; break;1499case XOR: Result = "!xor"; break;1500case SHL: Result = "!shl"; break;1501case SRA: Result = "!sra"; break;1502case SRL: Result = "!srl"; break;1503case EQ: Result = "!eq"; break;1504case NE: Result = "!ne"; break;1505case LE: Result = "!le"; break;1506case LT: Result = "!lt"; break;1507case GE: Result = "!ge"; break;1508case GT: Result = "!gt"; break;1509case LISTCONCAT: Result = "!listconcat"; break;1510case LISTSPLAT: Result = "!listsplat"; break;1511case LISTREMOVE:1512Result = "!listremove";1513break;1514case STRCONCAT: Result = "!strconcat"; break;1515case INTERLEAVE: Result = "!interleave"; break;1516case SETDAGOP: Result = "!setdagop"; break;1517case GETDAGARG:1518Result = "!getdagarg<" + getType()->getAsString() + ">";1519break;1520case GETDAGNAME:1521Result = "!getdagname";1522break;1523}1524return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";1525}15261527static void1528ProfileTernOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *MHS,1529Init *RHS, RecTy *Type) {1530ID.AddInteger(Opcode);1531ID.AddPointer(LHS);1532ID.AddPointer(MHS);1533ID.AddPointer(RHS);1534ID.AddPointer(Type);1535}15361537TernOpInit *TernOpInit::get(TernaryOp Opc, Init *LHS, Init *MHS, Init *RHS,1538RecTy *Type) {1539FoldingSetNodeID ID;1540ProfileTernOpInit(ID, Opc, LHS, MHS, RHS, Type);15411542detail::RecordKeeperImpl &RK = LHS->getRecordKeeper().getImpl();1543void *IP = nullptr;1544if (TernOpInit *I = RK.TheTernOpInitPool.FindNodeOrInsertPos(ID, IP))1545return I;15461547TernOpInit *I = new (RK.Allocator) TernOpInit(Opc, LHS, MHS, RHS, Type);1548RK.TheTernOpInitPool.InsertNode(I, IP);1549return I;1550}15511552void TernOpInit::Profile(FoldingSetNodeID &ID) const {1553ProfileTernOpInit(ID, getOpcode(), getLHS(), getMHS(), getRHS(), getType());1554}15551556static Init *ItemApply(Init *LHS, Init *MHSe, Init *RHS, Record *CurRec) {1557MapResolver R(CurRec);1558R.set(LHS, MHSe);1559return RHS->resolveReferences(R);1560}15611562static Init *ForeachDagApply(Init *LHS, DagInit *MHSd, Init *RHS,1563Record *CurRec) {1564bool Change = false;1565Init *Val = ItemApply(LHS, MHSd->getOperator(), RHS, CurRec);1566if (Val != MHSd->getOperator())1567Change = true;15681569SmallVector<std::pair<Init *, StringInit *>, 8> NewArgs;1570for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {1571Init *Arg = MHSd->getArg(i);1572Init *NewArg;1573StringInit *ArgName = MHSd->getArgName(i);15741575if (DagInit *Argd = dyn_cast<DagInit>(Arg))1576NewArg = ForeachDagApply(LHS, Argd, RHS, CurRec);1577else1578NewArg = ItemApply(LHS, Arg, RHS, CurRec);15791580NewArgs.push_back(std::make_pair(NewArg, ArgName));1581if (Arg != NewArg)1582Change = true;1583}15841585if (Change)1586return DagInit::get(Val, nullptr, NewArgs);1587return MHSd;1588}15891590// Applies RHS to all elements of MHS, using LHS as a temp variable.1591static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,1592Record *CurRec) {1593if (DagInit *MHSd = dyn_cast<DagInit>(MHS))1594return ForeachDagApply(LHS, MHSd, RHS, CurRec);15951596if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) {1597SmallVector<Init *, 8> NewList(MHSl->begin(), MHSl->end());15981599for (Init *&Item : NewList) {1600Init *NewItem = ItemApply(LHS, Item, RHS, CurRec);1601if (NewItem != Item)1602Item = NewItem;1603}1604return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());1605}16061607return nullptr;1608}16091610// Evaluates RHS for all elements of MHS, using LHS as a temp variable.1611// Creates a new list with the elements that evaluated to true.1612static Init *FilterHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,1613Record *CurRec) {1614if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) {1615SmallVector<Init *, 8> NewList;16161617for (Init *Item : MHSl->getValues()) {1618Init *Include = ItemApply(LHS, Item, RHS, CurRec);1619if (!Include)1620return nullptr;1621if (IntInit *IncludeInt =1622dyn_cast_or_null<IntInit>(Include->convertInitializerTo(1623IntRecTy::get(LHS->getRecordKeeper())))) {1624if (IncludeInt->getValue())1625NewList.push_back(Item);1626} else {1627return nullptr;1628}1629}1630return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());1631}16321633return nullptr;1634}16351636Init *TernOpInit::Fold(Record *CurRec) const {1637RecordKeeper &RK = getRecordKeeper();1638switch (getOpcode()) {1639case SUBST: {1640DefInit *LHSd = dyn_cast<DefInit>(LHS);1641VarInit *LHSv = dyn_cast<VarInit>(LHS);1642StringInit *LHSs = dyn_cast<StringInit>(LHS);16431644DefInit *MHSd = dyn_cast<DefInit>(MHS);1645VarInit *MHSv = dyn_cast<VarInit>(MHS);1646StringInit *MHSs = dyn_cast<StringInit>(MHS);16471648DefInit *RHSd = dyn_cast<DefInit>(RHS);1649VarInit *RHSv = dyn_cast<VarInit>(RHS);1650StringInit *RHSs = dyn_cast<StringInit>(RHS);16511652if (LHSd && MHSd && RHSd) {1653Record *Val = RHSd->getDef();1654if (LHSd->getAsString() == RHSd->getAsString())1655Val = MHSd->getDef();1656return DefInit::get(Val);1657}1658if (LHSv && MHSv && RHSv) {1659std::string Val = std::string(RHSv->getName());1660if (LHSv->getAsString() == RHSv->getAsString())1661Val = std::string(MHSv->getName());1662return VarInit::get(Val, getType());1663}1664if (LHSs && MHSs && RHSs) {1665std::string Val = std::string(RHSs->getValue());16661667std::string::size_type found;1668std::string::size_type idx = 0;1669while (true) {1670found = Val.find(std::string(LHSs->getValue()), idx);1671if (found == std::string::npos)1672break;1673Val.replace(found, LHSs->getValue().size(),1674std::string(MHSs->getValue()));1675idx = found + MHSs->getValue().size();1676}16771678return StringInit::get(RK, Val);1679}1680break;1681}16821683case FOREACH: {1684if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(), CurRec))1685return Result;1686break;1687}16881689case FILTER: {1690if (Init *Result = FilterHelper(LHS, MHS, RHS, getType(), CurRec))1691return Result;1692break;1693}16941695case IF: {1696if (IntInit *LHSi = dyn_cast_or_null<IntInit>(1697LHS->convertInitializerTo(IntRecTy::get(RK)))) {1698if (LHSi->getValue())1699return MHS;1700return RHS;1701}1702break;1703}17041705case DAG: {1706ListInit *MHSl = dyn_cast<ListInit>(MHS);1707ListInit *RHSl = dyn_cast<ListInit>(RHS);1708bool MHSok = MHSl || isa<UnsetInit>(MHS);1709bool RHSok = RHSl || isa<UnsetInit>(RHS);17101711if (isa<UnsetInit>(MHS) && isa<UnsetInit>(RHS))1712break; // Typically prevented by the parser, but might happen with template args17131714if (MHSok && RHSok && (!MHSl || !RHSl || MHSl->size() == RHSl->size())) {1715SmallVector<std::pair<Init *, StringInit *>, 8> Children;1716unsigned Size = MHSl ? MHSl->size() : RHSl->size();1717for (unsigned i = 0; i != Size; ++i) {1718Init *Node = MHSl ? MHSl->getElement(i) : UnsetInit::get(RK);1719Init *Name = RHSl ? RHSl->getElement(i) : UnsetInit::get(RK);1720if (!isa<StringInit>(Name) && !isa<UnsetInit>(Name))1721return const_cast<TernOpInit *>(this);1722Children.emplace_back(Node, dyn_cast<StringInit>(Name));1723}1724return DagInit::get(LHS, nullptr, Children);1725}1726break;1727}17281729case RANGE: {1730auto *LHSi = dyn_cast<IntInit>(LHS);1731auto *MHSi = dyn_cast<IntInit>(MHS);1732auto *RHSi = dyn_cast<IntInit>(RHS);1733if (!LHSi || !MHSi || !RHSi)1734break;17351736auto Start = LHSi->getValue();1737auto End = MHSi->getValue();1738auto Step = RHSi->getValue();1739if (Step == 0)1740PrintError(CurRec->getLoc(), "Step of !range can't be 0");17411742SmallVector<Init *, 8> Args;1743if (Start < End && Step > 0) {1744Args.reserve((End - Start) / Step);1745for (auto I = Start; I < End; I += Step)1746Args.push_back(IntInit::get(getRecordKeeper(), I));1747} else if (Start > End && Step < 0) {1748Args.reserve((Start - End) / -Step);1749for (auto I = Start; I > End; I += Step)1750Args.push_back(IntInit::get(getRecordKeeper(), I));1751} else {1752// Empty set1753}1754return ListInit::get(Args, LHSi->getType());1755}17561757case SUBSTR: {1758StringInit *LHSs = dyn_cast<StringInit>(LHS);1759IntInit *MHSi = dyn_cast<IntInit>(MHS);1760IntInit *RHSi = dyn_cast<IntInit>(RHS);1761if (LHSs && MHSi && RHSi) {1762int64_t StringSize = LHSs->getValue().size();1763int64_t Start = MHSi->getValue();1764int64_t Length = RHSi->getValue();1765if (Start < 0 || Start > StringSize)1766PrintError(CurRec->getLoc(),1767Twine("!substr start position is out of range 0...") +1768std::to_string(StringSize) + ": " +1769std::to_string(Start));1770if (Length < 0)1771PrintError(CurRec->getLoc(), "!substr length must be nonnegative");1772return StringInit::get(RK, LHSs->getValue().substr(Start, Length),1773LHSs->getFormat());1774}1775break;1776}17771778case FIND: {1779StringInit *LHSs = dyn_cast<StringInit>(LHS);1780StringInit *MHSs = dyn_cast<StringInit>(MHS);1781IntInit *RHSi = dyn_cast<IntInit>(RHS);1782if (LHSs && MHSs && RHSi) {1783int64_t SourceSize = LHSs->getValue().size();1784int64_t Start = RHSi->getValue();1785if (Start < 0 || Start > SourceSize)1786PrintError(CurRec->getLoc(),1787Twine("!find start position is out of range 0...") +1788std::to_string(SourceSize) + ": " +1789std::to_string(Start));1790auto I = LHSs->getValue().find(MHSs->getValue(), Start);1791if (I == std::string::npos)1792return IntInit::get(RK, -1);1793return IntInit::get(RK, I);1794}1795break;1796}17971798case SETDAGARG: {1799DagInit *Dag = dyn_cast<DagInit>(LHS);1800if (Dag && isa<IntInit, StringInit>(MHS)) {1801std::string Error;1802auto ArgNo = getDagArgNoByKey(Dag, MHS, Error);1803if (!ArgNo)1804PrintFatalError(CurRec->getLoc(), "!setdagarg " + Error);18051806assert(*ArgNo < Dag->getNumArgs());18071808SmallVector<Init *, 8> Args(Dag->getArgs());1809SmallVector<StringInit *, 8> Names(Dag->getArgNames());1810Args[*ArgNo] = RHS;1811return DagInit::get(Dag->getOperator(), Dag->getName(), Args, Names);1812}1813break;1814}18151816case SETDAGNAME: {1817DagInit *Dag = dyn_cast<DagInit>(LHS);1818if (Dag && isa<IntInit, StringInit>(MHS)) {1819std::string Error;1820auto ArgNo = getDagArgNoByKey(Dag, MHS, Error);1821if (!ArgNo)1822PrintFatalError(CurRec->getLoc(), "!setdagname " + Error);18231824assert(*ArgNo < Dag->getNumArgs());18251826SmallVector<Init *, 8> Args(Dag->getArgs());1827SmallVector<StringInit *, 8> Names(Dag->getArgNames());1828Names[*ArgNo] = dyn_cast<StringInit>(RHS);1829return DagInit::get(Dag->getOperator(), Dag->getName(), Args, Names);1830}1831break;1832}1833}18341835return const_cast<TernOpInit *>(this);1836}18371838Init *TernOpInit::resolveReferences(Resolver &R) const {1839Init *lhs = LHS->resolveReferences(R);18401841if (getOpcode() == IF && lhs != LHS) {1842if (IntInit *Value = dyn_cast_or_null<IntInit>(1843lhs->convertInitializerTo(IntRecTy::get(getRecordKeeper())))) {1844// Short-circuit1845if (Value->getValue())1846return MHS->resolveReferences(R);1847return RHS->resolveReferences(R);1848}1849}18501851Init *mhs = MHS->resolveReferences(R);1852Init *rhs;18531854if (getOpcode() == FOREACH || getOpcode() == FILTER) {1855ShadowResolver SR(R);1856SR.addShadow(lhs);1857rhs = RHS->resolveReferences(SR);1858} else {1859rhs = RHS->resolveReferences(R);1860}18611862if (LHS != lhs || MHS != mhs || RHS != rhs)1863return (TernOpInit::get(getOpcode(), lhs, mhs, rhs, getType()))1864->Fold(R.getCurrentRecord());1865return const_cast<TernOpInit *>(this);1866}18671868std::string TernOpInit::getAsString() const {1869std::string Result;1870bool UnquotedLHS = false;1871switch (getOpcode()) {1872case DAG: Result = "!dag"; break;1873case FILTER: Result = "!filter"; UnquotedLHS = true; break;1874case FOREACH: Result = "!foreach"; UnquotedLHS = true; break;1875case IF: Result = "!if"; break;1876case RANGE:1877Result = "!range";1878break;1879case SUBST: Result = "!subst"; break;1880case SUBSTR: Result = "!substr"; break;1881case FIND: Result = "!find"; break;1882case SETDAGARG:1883Result = "!setdagarg";1884break;1885case SETDAGNAME:1886Result = "!setdagname";1887break;1888}1889return (Result + "(" +1890(UnquotedLHS ? LHS->getAsUnquotedString() : LHS->getAsString()) +1891", " + MHS->getAsString() + ", " + RHS->getAsString() + ")");1892}18931894static void ProfileFoldOpInit(FoldingSetNodeID &ID, Init *Start, Init *List,1895Init *A, Init *B, Init *Expr, RecTy *Type) {1896ID.AddPointer(Start);1897ID.AddPointer(List);1898ID.AddPointer(A);1899ID.AddPointer(B);1900ID.AddPointer(Expr);1901ID.AddPointer(Type);1902}19031904FoldOpInit *FoldOpInit::get(Init *Start, Init *List, Init *A, Init *B,1905Init *Expr, RecTy *Type) {1906FoldingSetNodeID ID;1907ProfileFoldOpInit(ID, Start, List, A, B, Expr, Type);19081909detail::RecordKeeperImpl &RK = Start->getRecordKeeper().getImpl();1910void *IP = nullptr;1911if (FoldOpInit *I = RK.TheFoldOpInitPool.FindNodeOrInsertPos(ID, IP))1912return I;19131914FoldOpInit *I = new (RK.Allocator) FoldOpInit(Start, List, A, B, Expr, Type);1915RK.TheFoldOpInitPool.InsertNode(I, IP);1916return I;1917}19181919void FoldOpInit::Profile(FoldingSetNodeID &ID) const {1920ProfileFoldOpInit(ID, Start, List, A, B, Expr, getType());1921}19221923Init *FoldOpInit::Fold(Record *CurRec) const {1924if (ListInit *LI = dyn_cast<ListInit>(List)) {1925Init *Accum = Start;1926for (Init *Elt : *LI) {1927MapResolver R(CurRec);1928R.set(A, Accum);1929R.set(B, Elt);1930Accum = Expr->resolveReferences(R);1931}1932return Accum;1933}1934return const_cast<FoldOpInit *>(this);1935}19361937Init *FoldOpInit::resolveReferences(Resolver &R) const {1938Init *NewStart = Start->resolveReferences(R);1939Init *NewList = List->resolveReferences(R);1940ShadowResolver SR(R);1941SR.addShadow(A);1942SR.addShadow(B);1943Init *NewExpr = Expr->resolveReferences(SR);19441945if (Start == NewStart && List == NewList && Expr == NewExpr)1946return const_cast<FoldOpInit *>(this);19471948return get(NewStart, NewList, A, B, NewExpr, getType())1949->Fold(R.getCurrentRecord());1950}19511952Init *FoldOpInit::getBit(unsigned Bit) const {1953return VarBitInit::get(const_cast<FoldOpInit *>(this), Bit);1954}19551956std::string FoldOpInit::getAsString() const {1957return (Twine("!foldl(") + Start->getAsString() + ", " + List->getAsString() +1958", " + A->getAsUnquotedString() + ", " + B->getAsUnquotedString() +1959", " + Expr->getAsString() + ")")1960.str();1961}19621963static void ProfileIsAOpInit(FoldingSetNodeID &ID, RecTy *CheckType,1964Init *Expr) {1965ID.AddPointer(CheckType);1966ID.AddPointer(Expr);1967}19681969IsAOpInit *IsAOpInit::get(RecTy *CheckType, Init *Expr) {19701971FoldingSetNodeID ID;1972ProfileIsAOpInit(ID, CheckType, Expr);19731974detail::RecordKeeperImpl &RK = Expr->getRecordKeeper().getImpl();1975void *IP = nullptr;1976if (IsAOpInit *I = RK.TheIsAOpInitPool.FindNodeOrInsertPos(ID, IP))1977return I;19781979IsAOpInit *I = new (RK.Allocator) IsAOpInit(CheckType, Expr);1980RK.TheIsAOpInitPool.InsertNode(I, IP);1981return I;1982}19831984void IsAOpInit::Profile(FoldingSetNodeID &ID) const {1985ProfileIsAOpInit(ID, CheckType, Expr);1986}19871988Init *IsAOpInit::Fold() const {1989if (TypedInit *TI = dyn_cast<TypedInit>(Expr)) {1990// Is the expression type known to be (a subclass of) the desired type?1991if (TI->getType()->typeIsConvertibleTo(CheckType))1992return IntInit::get(getRecordKeeper(), 1);19931994if (isa<RecordRecTy>(CheckType)) {1995// If the target type is not a subclass of the expression type, or if1996// the expression has fully resolved to a record, we know that it can't1997// be of the required type.1998if (!CheckType->typeIsConvertibleTo(TI->getType()) || isa<DefInit>(Expr))1999return IntInit::get(getRecordKeeper(), 0);2000} else {2001// We treat non-record types as not castable.2002return IntInit::get(getRecordKeeper(), 0);2003}2004}2005return const_cast<IsAOpInit *>(this);2006}20072008Init *IsAOpInit::resolveReferences(Resolver &R) const {2009Init *NewExpr = Expr->resolveReferences(R);2010if (Expr != NewExpr)2011return get(CheckType, NewExpr)->Fold();2012return const_cast<IsAOpInit *>(this);2013}20142015Init *IsAOpInit::getBit(unsigned Bit) const {2016return VarBitInit::get(const_cast<IsAOpInit *>(this), Bit);2017}20182019std::string IsAOpInit::getAsString() const {2020return (Twine("!isa<") + CheckType->getAsString() + ">(" +2021Expr->getAsString() + ")")2022.str();2023}20242025static void ProfileExistsOpInit(FoldingSetNodeID &ID, RecTy *CheckType,2026Init *Expr) {2027ID.AddPointer(CheckType);2028ID.AddPointer(Expr);2029}20302031ExistsOpInit *ExistsOpInit::get(RecTy *CheckType, Init *Expr) {2032FoldingSetNodeID ID;2033ProfileExistsOpInit(ID, CheckType, Expr);20342035detail::RecordKeeperImpl &RK = Expr->getRecordKeeper().getImpl();2036void *IP = nullptr;2037if (ExistsOpInit *I = RK.TheExistsOpInitPool.FindNodeOrInsertPos(ID, IP))2038return I;20392040ExistsOpInit *I = new (RK.Allocator) ExistsOpInit(CheckType, Expr);2041RK.TheExistsOpInitPool.InsertNode(I, IP);2042return I;2043}20442045void ExistsOpInit::Profile(FoldingSetNodeID &ID) const {2046ProfileExistsOpInit(ID, CheckType, Expr);2047}20482049Init *ExistsOpInit::Fold(Record *CurRec, bool IsFinal) const {2050if (StringInit *Name = dyn_cast<StringInit>(Expr)) {20512052// Look up all defined records to see if we can find one.2053Record *D = CheckType->getRecordKeeper().getDef(Name->getValue());2054if (D) {2055// Check if types are compatible.2056return IntInit::get(getRecordKeeper(),2057DefInit::get(D)->getType()->typeIsA(CheckType));2058}20592060if (CurRec) {2061// Self-references are allowed, but their resolution is delayed until2062// the final resolve to ensure that we get the correct type for them.2063auto *Anonymous = dyn_cast<AnonymousNameInit>(CurRec->getNameInit());2064if (Name == CurRec->getNameInit() ||2065(Anonymous && Name == Anonymous->getNameInit())) {2066if (!IsFinal)2067return const_cast<ExistsOpInit *>(this);20682069// No doubt that there exists a record, so we should check if types are2070// compatible.2071return IntInit::get(getRecordKeeper(),2072CurRec->getType()->typeIsA(CheckType));2073}2074}20752076if (IsFinal)2077return IntInit::get(getRecordKeeper(), 0);2078return const_cast<ExistsOpInit *>(this);2079}2080return const_cast<ExistsOpInit *>(this);2081}20822083Init *ExistsOpInit::resolveReferences(Resolver &R) const {2084Init *NewExpr = Expr->resolveReferences(R);2085if (Expr != NewExpr || R.isFinal())2086return get(CheckType, NewExpr)->Fold(R.getCurrentRecord(), R.isFinal());2087return const_cast<ExistsOpInit *>(this);2088}20892090Init *ExistsOpInit::getBit(unsigned Bit) const {2091return VarBitInit::get(const_cast<ExistsOpInit *>(this), Bit);2092}20932094std::string ExistsOpInit::getAsString() const {2095return (Twine("!exists<") + CheckType->getAsString() + ">(" +2096Expr->getAsString() + ")")2097.str();2098}20992100RecTy *TypedInit::getFieldType(StringInit *FieldName) const {2101if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType())) {2102for (Record *Rec : RecordType->getClasses()) {2103if (RecordVal *Field = Rec->getValue(FieldName))2104return Field->getType();2105}2106}2107return nullptr;2108}21092110Init *2111TypedInit::convertInitializerTo(RecTy *Ty) const {2112if (getType() == Ty || getType()->typeIsA(Ty))2113return const_cast<TypedInit *>(this);21142115if (isa<BitRecTy>(getType()) && isa<BitsRecTy>(Ty) &&2116cast<BitsRecTy>(Ty)->getNumBits() == 1)2117return BitsInit::get(getRecordKeeper(), {const_cast<TypedInit *>(this)});21182119return nullptr;2120}21212122Init *TypedInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {2123BitsRecTy *T = dyn_cast<BitsRecTy>(getType());2124if (!T) return nullptr; // Cannot subscript a non-bits variable.2125unsigned NumBits = T->getNumBits();21262127SmallVector<Init *, 16> NewBits;2128NewBits.reserve(Bits.size());2129for (unsigned Bit : Bits) {2130if (Bit >= NumBits)2131return nullptr;21322133NewBits.push_back(VarBitInit::get(const_cast<TypedInit *>(this), Bit));2134}2135return BitsInit::get(getRecordKeeper(), NewBits);2136}21372138Init *TypedInit::getCastTo(RecTy *Ty) const {2139// Handle the common case quickly2140if (getType() == Ty || getType()->typeIsA(Ty))2141return const_cast<TypedInit *>(this);21422143if (Init *Converted = convertInitializerTo(Ty)) {2144assert(!isa<TypedInit>(Converted) ||2145cast<TypedInit>(Converted)->getType()->typeIsA(Ty));2146return Converted;2147}21482149if (!getType()->typeIsConvertibleTo(Ty))2150return nullptr;21512152return UnOpInit::get(UnOpInit::CAST, const_cast<TypedInit *>(this), Ty)2153->Fold(nullptr);2154}21552156VarInit *VarInit::get(StringRef VN, RecTy *T) {2157Init *Value = StringInit::get(T->getRecordKeeper(), VN);2158return VarInit::get(Value, T);2159}21602161VarInit *VarInit::get(Init *VN, RecTy *T) {2162detail::RecordKeeperImpl &RK = T->getRecordKeeper().getImpl();2163VarInit *&I = RK.TheVarInitPool[std::make_pair(T, VN)];2164if (!I)2165I = new (RK.Allocator) VarInit(VN, T);2166return I;2167}21682169StringRef VarInit::getName() const {2170StringInit *NameString = cast<StringInit>(getNameInit());2171return NameString->getValue();2172}21732174Init *VarInit::getBit(unsigned Bit) const {2175if (getType() == BitRecTy::get(getRecordKeeper()))2176return const_cast<VarInit*>(this);2177return VarBitInit::get(const_cast<VarInit*>(this), Bit);2178}21792180Init *VarInit::resolveReferences(Resolver &R) const {2181if (Init *Val = R.resolve(VarName))2182return Val;2183return const_cast<VarInit *>(this);2184}21852186VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {2187detail::RecordKeeperImpl &RK = T->getRecordKeeper().getImpl();2188VarBitInit *&I = RK.TheVarBitInitPool[std::make_pair(T, B)];2189if (!I)2190I = new (RK.Allocator) VarBitInit(T, B);2191return I;2192}21932194std::string VarBitInit::getAsString() const {2195return TI->getAsString() + "{" + utostr(Bit) + "}";2196}21972198Init *VarBitInit::resolveReferences(Resolver &R) const {2199Init *I = TI->resolveReferences(R);2200if (TI != I)2201return I->getBit(getBitNum());22022203return const_cast<VarBitInit*>(this);2204}22052206DefInit::DefInit(Record *D)2207: TypedInit(IK_DefInit, D->getType()), Def(D) {}22082209DefInit *DefInit::get(Record *R) {2210return R->getDefInit();2211}22122213Init *DefInit::convertInitializerTo(RecTy *Ty) const {2214if (auto *RRT = dyn_cast<RecordRecTy>(Ty))2215if (getType()->typeIsConvertibleTo(RRT))2216return const_cast<DefInit *>(this);2217return nullptr;2218}22192220RecTy *DefInit::getFieldType(StringInit *FieldName) const {2221if (const RecordVal *RV = Def->getValue(FieldName))2222return RV->getType();2223return nullptr;2224}22252226std::string DefInit::getAsString() const { return std::string(Def->getName()); }22272228static void ProfileVarDefInit(FoldingSetNodeID &ID, Record *Class,2229ArrayRef<ArgumentInit *> Args) {2230ID.AddInteger(Args.size());2231ID.AddPointer(Class);22322233for (Init *I : Args)2234ID.AddPointer(I);2235}22362237VarDefInit::VarDefInit(Record *Class, unsigned N)2238: TypedInit(IK_VarDefInit, RecordRecTy::get(Class)), Class(Class),2239NumArgs(N) {}22402241VarDefInit *VarDefInit::get(Record *Class, ArrayRef<ArgumentInit *> Args) {2242FoldingSetNodeID ID;2243ProfileVarDefInit(ID, Class, Args);22442245detail::RecordKeeperImpl &RK = Class->getRecords().getImpl();2246void *IP = nullptr;2247if (VarDefInit *I = RK.TheVarDefInitPool.FindNodeOrInsertPos(ID, IP))2248return I;22492250void *Mem = RK.Allocator.Allocate(2251totalSizeToAlloc<ArgumentInit *>(Args.size()), alignof(VarDefInit));2252VarDefInit *I = new (Mem) VarDefInit(Class, Args.size());2253std::uninitialized_copy(Args.begin(), Args.end(),2254I->getTrailingObjects<ArgumentInit *>());2255RK.TheVarDefInitPool.InsertNode(I, IP);2256return I;2257}22582259void VarDefInit::Profile(FoldingSetNodeID &ID) const {2260ProfileVarDefInit(ID, Class, args());2261}22622263DefInit *VarDefInit::instantiate() {2264if (!Def) {2265RecordKeeper &Records = Class->getRecords();2266auto NewRecOwner =2267std::make_unique<Record>(Records.getNewAnonymousName(), Class->getLoc(),2268Records, Record::RK_AnonymousDef);2269Record *NewRec = NewRecOwner.get();22702271// Copy values from class to instance2272for (const RecordVal &Val : Class->getValues())2273NewRec->addValue(Val);22742275// Copy assertions from class to instance.2276NewRec->appendAssertions(Class);22772278// Copy dumps from class to instance.2279NewRec->appendDumps(Class);22802281// Substitute and resolve template arguments2282ArrayRef<Init *> TArgs = Class->getTemplateArgs();2283MapResolver R(NewRec);22842285for (Init *Arg : TArgs) {2286R.set(Arg, NewRec->getValue(Arg)->getValue());2287NewRec->removeValue(Arg);2288}22892290for (auto *Arg : args()) {2291if (Arg->isPositional())2292R.set(TArgs[Arg->getIndex()], Arg->getValue());2293if (Arg->isNamed())2294R.set(Arg->getName(), Arg->getValue());2295}22962297NewRec->resolveReferences(R);22982299// Add superclasses.2300ArrayRef<std::pair<Record *, SMRange>> SCs = Class->getSuperClasses();2301for (const auto &SCPair : SCs)2302NewRec->addSuperClass(SCPair.first, SCPair.second);23032304NewRec->addSuperClass(Class,2305SMRange(Class->getLoc().back(),2306Class->getLoc().back()));23072308// Resolve internal references and store in record keeper2309NewRec->resolveReferences();2310Records.addDef(std::move(NewRecOwner));23112312// Check the assertions.2313NewRec->checkRecordAssertions();23142315// Check the assertions.2316NewRec->emitRecordDumps();23172318Def = DefInit::get(NewRec);2319}23202321return Def;2322}23232324Init *VarDefInit::resolveReferences(Resolver &R) const {2325TrackUnresolvedResolver UR(&R);2326bool Changed = false;2327SmallVector<ArgumentInit *, 8> NewArgs;2328NewArgs.reserve(args_size());23292330for (ArgumentInit *Arg : args()) {2331auto *NewArg = cast<ArgumentInit>(Arg->resolveReferences(UR));2332NewArgs.push_back(NewArg);2333Changed |= NewArg != Arg;2334}23352336if (Changed) {2337auto New = VarDefInit::get(Class, NewArgs);2338if (!UR.foundUnresolved())2339return New->instantiate();2340return New;2341}2342return const_cast<VarDefInit *>(this);2343}23442345Init *VarDefInit::Fold() const {2346if (Def)2347return Def;23482349TrackUnresolvedResolver R;2350for (Init *Arg : args())2351Arg->resolveReferences(R);23522353if (!R.foundUnresolved())2354return const_cast<VarDefInit *>(this)->instantiate();2355return const_cast<VarDefInit *>(this);2356}23572358std::string VarDefInit::getAsString() const {2359std::string Result = Class->getNameInitAsString() + "<";2360const char *sep = "";2361for (Init *Arg : args()) {2362Result += sep;2363sep = ", ";2364Result += Arg->getAsString();2365}2366return Result + ">";2367}23682369FieldInit *FieldInit::get(Init *R, StringInit *FN) {2370detail::RecordKeeperImpl &RK = R->getRecordKeeper().getImpl();2371FieldInit *&I = RK.TheFieldInitPool[std::make_pair(R, FN)];2372if (!I)2373I = new (RK.Allocator) FieldInit(R, FN);2374return I;2375}23762377Init *FieldInit::getBit(unsigned Bit) const {2378if (getType() == BitRecTy::get(getRecordKeeper()))2379return const_cast<FieldInit*>(this);2380return VarBitInit::get(const_cast<FieldInit*>(this), Bit);2381}23822383Init *FieldInit::resolveReferences(Resolver &R) const {2384Init *NewRec = Rec->resolveReferences(R);2385if (NewRec != Rec)2386return FieldInit::get(NewRec, FieldName)->Fold(R.getCurrentRecord());2387return const_cast<FieldInit *>(this);2388}23892390Init *FieldInit::Fold(Record *CurRec) const {2391if (DefInit *DI = dyn_cast<DefInit>(Rec)) {2392Record *Def = DI->getDef();2393if (Def == CurRec)2394PrintFatalError(CurRec->getLoc(),2395Twine("Attempting to access field '") +2396FieldName->getAsUnquotedString() + "' of '" +2397Rec->getAsString() + "' is a forbidden self-reference");2398Init *FieldVal = Def->getValue(FieldName)->getValue();2399if (FieldVal->isConcrete())2400return FieldVal;2401}2402return const_cast<FieldInit *>(this);2403}24042405bool FieldInit::isConcrete() const {2406if (DefInit *DI = dyn_cast<DefInit>(Rec)) {2407Init *FieldVal = DI->getDef()->getValue(FieldName)->getValue();2408return FieldVal->isConcrete();2409}2410return false;2411}24122413static void ProfileCondOpInit(FoldingSetNodeID &ID,2414ArrayRef<Init *> CondRange,2415ArrayRef<Init *> ValRange,2416const RecTy *ValType) {2417assert(CondRange.size() == ValRange.size() &&2418"Number of conditions and values must match!");2419ID.AddPointer(ValType);2420ArrayRef<Init *>::iterator Case = CondRange.begin();2421ArrayRef<Init *>::iterator Val = ValRange.begin();24222423while (Case != CondRange.end()) {2424ID.AddPointer(*Case++);2425ID.AddPointer(*Val++);2426}2427}24282429void CondOpInit::Profile(FoldingSetNodeID &ID) const {2430ProfileCondOpInit(ID, ArrayRef(getTrailingObjects<Init *>(), NumConds),2431ArrayRef(getTrailingObjects<Init *>() + NumConds, NumConds),2432ValType);2433}24342435CondOpInit *CondOpInit::get(ArrayRef<Init *> CondRange,2436ArrayRef<Init *> ValRange, RecTy *Ty) {2437assert(CondRange.size() == ValRange.size() &&2438"Number of conditions and values must match!");24392440FoldingSetNodeID ID;2441ProfileCondOpInit(ID, CondRange, ValRange, Ty);24422443detail::RecordKeeperImpl &RK = Ty->getRecordKeeper().getImpl();2444void *IP = nullptr;2445if (CondOpInit *I = RK.TheCondOpInitPool.FindNodeOrInsertPos(ID, IP))2446return I;24472448void *Mem = RK.Allocator.Allocate(2449totalSizeToAlloc<Init *>(2 * CondRange.size()), alignof(BitsInit));2450CondOpInit *I = new(Mem) CondOpInit(CondRange.size(), Ty);24512452std::uninitialized_copy(CondRange.begin(), CondRange.end(),2453I->getTrailingObjects<Init *>());2454std::uninitialized_copy(ValRange.begin(), ValRange.end(),2455I->getTrailingObjects<Init *>()+CondRange.size());2456RK.TheCondOpInitPool.InsertNode(I, IP);2457return I;2458}24592460Init *CondOpInit::resolveReferences(Resolver &R) const {2461SmallVector<Init*, 4> NewConds;2462bool Changed = false;2463for (const Init *Case : getConds()) {2464Init *NewCase = Case->resolveReferences(R);2465NewConds.push_back(NewCase);2466Changed |= NewCase != Case;2467}24682469SmallVector<Init*, 4> NewVals;2470for (const Init *Val : getVals()) {2471Init *NewVal = Val->resolveReferences(R);2472NewVals.push_back(NewVal);2473Changed |= NewVal != Val;2474}24752476if (Changed)2477return (CondOpInit::get(NewConds, NewVals,2478getValType()))->Fold(R.getCurrentRecord());24792480return const_cast<CondOpInit *>(this);2481}24822483Init *CondOpInit::Fold(Record *CurRec) const {2484RecordKeeper &RK = getRecordKeeper();2485for ( unsigned i = 0; i < NumConds; ++i) {2486Init *Cond = getCond(i);2487Init *Val = getVal(i);24882489if (IntInit *CondI = dyn_cast_or_null<IntInit>(2490Cond->convertInitializerTo(IntRecTy::get(RK)))) {2491if (CondI->getValue())2492return Val->convertInitializerTo(getValType());2493} else {2494return const_cast<CondOpInit *>(this);2495}2496}24972498PrintFatalError(CurRec->getLoc(),2499CurRec->getNameInitAsString() +2500" does not have any true condition in:" +2501this->getAsString());2502return nullptr;2503}25042505bool CondOpInit::isConcrete() const {2506for (const Init *Case : getConds())2507if (!Case->isConcrete())2508return false;25092510for (const Init *Val : getVals())2511if (!Val->isConcrete())2512return false;25132514return true;2515}25162517bool CondOpInit::isComplete() const {2518for (const Init *Case : getConds())2519if (!Case->isComplete())2520return false;25212522for (const Init *Val : getVals())2523if (!Val->isConcrete())2524return false;25252526return true;2527}25282529std::string CondOpInit::getAsString() const {2530std::string Result = "!cond(";2531for (unsigned i = 0; i < getNumConds(); i++) {2532Result += getCond(i)->getAsString() + ": ";2533Result += getVal(i)->getAsString();2534if (i != getNumConds()-1)2535Result += ", ";2536}2537return Result + ")";2538}25392540Init *CondOpInit::getBit(unsigned Bit) const {2541return VarBitInit::get(const_cast<CondOpInit *>(this), Bit);2542}25432544static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, StringInit *VN,2545ArrayRef<Init *> ArgRange,2546ArrayRef<StringInit *> NameRange) {2547ID.AddPointer(V);2548ID.AddPointer(VN);25492550ArrayRef<Init *>::iterator Arg = ArgRange.begin();2551ArrayRef<StringInit *>::iterator Name = NameRange.begin();2552while (Arg != ArgRange.end()) {2553assert(Name != NameRange.end() && "Arg name underflow!");2554ID.AddPointer(*Arg++);2555ID.AddPointer(*Name++);2556}2557assert(Name == NameRange.end() && "Arg name overflow!");2558}25592560DagInit *DagInit::get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,2561ArrayRef<StringInit *> NameRange) {2562assert(ArgRange.size() == NameRange.size());2563FoldingSetNodeID ID;2564ProfileDagInit(ID, V, VN, ArgRange, NameRange);25652566detail::RecordKeeperImpl &RK = V->getRecordKeeper().getImpl();2567void *IP = nullptr;2568if (DagInit *I = RK.TheDagInitPool.FindNodeOrInsertPos(ID, IP))2569return I;25702571void *Mem = RK.Allocator.Allocate(2572totalSizeToAlloc<Init *, StringInit *>(ArgRange.size(), NameRange.size()),2573alignof(BitsInit));2574DagInit *I = new (Mem) DagInit(V, VN, ArgRange.size(), NameRange.size());2575std::uninitialized_copy(ArgRange.begin(), ArgRange.end(),2576I->getTrailingObjects<Init *>());2577std::uninitialized_copy(NameRange.begin(), NameRange.end(),2578I->getTrailingObjects<StringInit *>());2579RK.TheDagInitPool.InsertNode(I, IP);2580return I;2581}25822583DagInit *2584DagInit::get(Init *V, StringInit *VN,2585ArrayRef<std::pair<Init*, StringInit*>> args) {2586SmallVector<Init *, 8> Args;2587SmallVector<StringInit *, 8> Names;25882589for (const auto &Arg : args) {2590Args.push_back(Arg.first);2591Names.push_back(Arg.second);2592}25932594return DagInit::get(V, VN, Args, Names);2595}25962597void DagInit::Profile(FoldingSetNodeID &ID) const {2598ProfileDagInit(ID, Val, ValName,2599ArrayRef(getTrailingObjects<Init *>(), NumArgs),2600ArrayRef(getTrailingObjects<StringInit *>(), NumArgNames));2601}26022603Record *DagInit::getOperatorAsDef(ArrayRef<SMLoc> Loc) const {2604if (DefInit *DefI = dyn_cast<DefInit>(Val))2605return DefI->getDef();2606PrintFatalError(Loc, "Expected record as operator");2607return nullptr;2608}26092610std::optional<unsigned> DagInit::getArgNo(StringRef Name) const {2611for (unsigned i = 0, e = getNumArgs(); i < e; ++i) {2612StringInit *ArgName = getArgName(i);2613if (ArgName && ArgName->getValue() == Name)2614return i;2615}2616return std::nullopt;2617}26182619Init *DagInit::resolveReferences(Resolver &R) const {2620SmallVector<Init*, 8> NewArgs;2621NewArgs.reserve(arg_size());2622bool ArgsChanged = false;2623for (const Init *Arg : getArgs()) {2624Init *NewArg = Arg->resolveReferences(R);2625NewArgs.push_back(NewArg);2626ArgsChanged |= NewArg != Arg;2627}26282629Init *Op = Val->resolveReferences(R);2630if (Op != Val || ArgsChanged)2631return DagInit::get(Op, ValName, NewArgs, getArgNames());26322633return const_cast<DagInit *>(this);2634}26352636bool DagInit::isConcrete() const {2637if (!Val->isConcrete())2638return false;2639for (const Init *Elt : getArgs()) {2640if (!Elt->isConcrete())2641return false;2642}2643return true;2644}26452646std::string DagInit::getAsString() const {2647std::string Result = "(" + Val->getAsString();2648if (ValName)2649Result += ":" + ValName->getAsUnquotedString();2650if (!arg_empty()) {2651Result += " " + getArg(0)->getAsString();2652if (getArgName(0)) Result += ":$" + getArgName(0)->getAsUnquotedString();2653for (unsigned i = 1, e = getNumArgs(); i != e; ++i) {2654Result += ", " + getArg(i)->getAsString();2655if (getArgName(i)) Result += ":$" + getArgName(i)->getAsUnquotedString();2656}2657}2658return Result + ")";2659}26602661//===----------------------------------------------------------------------===//2662// Other implementations2663//===----------------------------------------------------------------------===//26642665RecordVal::RecordVal(Init *N, RecTy *T, FieldKind K)2666: Name(N), TyAndKind(T, K) {2667setValue(UnsetInit::get(N->getRecordKeeper()));2668assert(Value && "Cannot create unset value for current type!");2669}26702671// This constructor accepts the same arguments as the above, but also2672// a source location.2673RecordVal::RecordVal(Init *N, SMLoc Loc, RecTy *T, FieldKind K)2674: Name(N), Loc(Loc), TyAndKind(T, K) {2675setValue(UnsetInit::get(N->getRecordKeeper()));2676assert(Value && "Cannot create unset value for current type!");2677}26782679StringRef RecordVal::getName() const {2680return cast<StringInit>(getNameInit())->getValue();2681}26822683std::string RecordVal::getPrintType() const {2684if (getType() == StringRecTy::get(getRecordKeeper())) {2685if (auto *StrInit = dyn_cast<StringInit>(Value)) {2686if (StrInit->hasCodeFormat())2687return "code";2688else2689return "string";2690} else {2691return "string";2692}2693} else {2694return TyAndKind.getPointer()->getAsString();2695}2696}26972698bool RecordVal::setValue(Init *V) {2699if (V) {2700Value = V->getCastTo(getType());2701if (Value) {2702assert(!isa<TypedInit>(Value) ||2703cast<TypedInit>(Value)->getType()->typeIsA(getType()));2704if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {2705if (!isa<BitsInit>(Value)) {2706SmallVector<Init *, 64> Bits;2707Bits.reserve(BTy->getNumBits());2708for (unsigned I = 0, E = BTy->getNumBits(); I < E; ++I)2709Bits.push_back(Value->getBit(I));2710Value = BitsInit::get(V->getRecordKeeper(), Bits);2711}2712}2713}2714return Value == nullptr;2715}2716Value = nullptr;2717return false;2718}27192720// This version of setValue takes a source location and resets the2721// location in the RecordVal.2722bool RecordVal::setValue(Init *V, SMLoc NewLoc) {2723Loc = NewLoc;2724if (V) {2725Value = V->getCastTo(getType());2726if (Value) {2727assert(!isa<TypedInit>(Value) ||2728cast<TypedInit>(Value)->getType()->typeIsA(getType()));2729if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {2730if (!isa<BitsInit>(Value)) {2731SmallVector<Init *, 64> Bits;2732Bits.reserve(BTy->getNumBits());2733for (unsigned I = 0, E = BTy->getNumBits(); I < E; ++I)2734Bits.push_back(Value->getBit(I));2735Value = BitsInit::get(getRecordKeeper(), Bits);2736}2737}2738}2739return Value == nullptr;2740}2741Value = nullptr;2742return false;2743}27442745#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)2746#include "llvm/TableGen/Record.h"2747LLVM_DUMP_METHOD void RecordVal::dump() const { errs() << *this; }2748#endif27492750void RecordVal::print(raw_ostream &OS, bool PrintSem) const {2751if (isNonconcreteOK()) OS << "field ";2752OS << getPrintType() << " " << getNameInitAsString();27532754if (getValue())2755OS << " = " << *getValue();27562757if (PrintSem) OS << ";\n";2758}27592760void Record::updateClassLoc(SMLoc Loc) {2761assert(Locs.size() == 1);2762ForwardDeclarationLocs.push_back(Locs.front());27632764Locs.clear();2765Locs.push_back(Loc);2766}27672768void Record::checkName() {2769// Ensure the record name has string type.2770const TypedInit *TypedName = cast<const TypedInit>(Name);2771if (!isa<StringRecTy>(TypedName->getType()))2772PrintFatalError(getLoc(), Twine("Record name '") + Name->getAsString() +2773"' is not a string!");2774}27752776RecordRecTy *Record::getType() {2777SmallVector<Record *, 4> DirectSCs;2778getDirectSuperClasses(DirectSCs);2779return RecordRecTy::get(TrackedRecords, DirectSCs);2780}27812782DefInit *Record::getDefInit() {2783if (!CorrespondingDefInit) {2784CorrespondingDefInit =2785new (TrackedRecords.getImpl().Allocator) DefInit(this);2786}2787return CorrespondingDefInit;2788}27892790unsigned Record::getNewUID(RecordKeeper &RK) {2791return RK.getImpl().LastRecordID++;2792}27932794void Record::setName(Init *NewName) {2795Name = NewName;2796checkName();2797// DO NOT resolve record values to the name at this point because2798// there might be default values for arguments of this def. Those2799// arguments might not have been resolved yet so we don't want to2800// prematurely assume values for those arguments were not passed to2801// this def.2802//2803// Nonetheless, it may be that some of this Record's values2804// reference the record name. Indeed, the reason for having the2805// record name be an Init is to provide this flexibility. The extra2806// resolve steps after completely instantiating defs takes care of2807// this. See TGParser::ParseDef and TGParser::ParseDefm.2808}28092810// NOTE for the next two functions:2811// Superclasses are in post-order, so the final one is a direct2812// superclass. All of its transitive superclases immediately precede it,2813// so we can step through the direct superclasses in reverse order.28142815bool Record::hasDirectSuperClass(const Record *Superclass) const {2816ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();28172818for (int I = SCs.size() - 1; I >= 0; --I) {2819const Record *SC = SCs[I].first;2820if (SC == Superclass)2821return true;2822I -= SC->getSuperClasses().size();2823}28242825return false;2826}28272828void Record::getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const {2829ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();28302831while (!SCs.empty()) {2832Record *SC = SCs.back().first;2833SCs = SCs.drop_back(1 + SC->getSuperClasses().size());2834Classes.push_back(SC);2835}2836}28372838void Record::resolveReferences(Resolver &R, const RecordVal *SkipVal) {2839Init *OldName = getNameInit();2840Init *NewName = Name->resolveReferences(R);2841if (NewName != OldName) {2842// Re-register with RecordKeeper.2843setName(NewName);2844}28452846// Resolve the field values.2847for (RecordVal &Value : Values) {2848if (SkipVal == &Value) // Skip resolve the same field as the given one2849continue;2850if (Init *V = Value.getValue()) {2851Init *VR = V->resolveReferences(R);2852if (Value.setValue(VR)) {2853std::string Type;2854if (TypedInit *VRT = dyn_cast<TypedInit>(VR))2855Type =2856(Twine("of type '") + VRT->getType()->getAsString() + "' ").str();2857PrintFatalError(2858getLoc(),2859Twine("Invalid value ") + Type + "found when setting field '" +2860Value.getNameInitAsString() + "' of type '" +2861Value.getType()->getAsString() +2862"' after resolving references: " + VR->getAsUnquotedString() +2863"\n");2864}2865}2866}28672868// Resolve the assertion expressions.2869for (auto &Assertion : Assertions) {2870Init *Value = Assertion.Condition->resolveReferences(R);2871Assertion.Condition = Value;2872Value = Assertion.Message->resolveReferences(R);2873Assertion.Message = Value;2874}2875// Resolve the dump expressions.2876for (auto &Dump : Dumps) {2877Init *Value = Dump.Message->resolveReferences(R);2878Dump.Message = Value;2879}2880}28812882void Record::resolveReferences(Init *NewName) {2883RecordResolver R(*this);2884R.setName(NewName);2885R.setFinal(true);2886resolveReferences(R);2887}28882889#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)2890LLVM_DUMP_METHOD void Record::dump() const { errs() << *this; }2891#endif28922893raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {2894OS << R.getNameInitAsString();28952896ArrayRef<Init *> TArgs = R.getTemplateArgs();2897if (!TArgs.empty()) {2898OS << "<";2899bool NeedComma = false;2900for (const Init *TA : TArgs) {2901if (NeedComma) OS << ", ";2902NeedComma = true;2903const RecordVal *RV = R.getValue(TA);2904assert(RV && "Template argument record not found??");2905RV->print(OS, false);2906}2907OS << ">";2908}29092910OS << " {";2911ArrayRef<std::pair<Record *, SMRange>> SC = R.getSuperClasses();2912if (!SC.empty()) {2913OS << "\t//";2914for (const auto &SuperPair : SC)2915OS << " " << SuperPair.first->getNameInitAsString();2916}2917OS << "\n";29182919for (const RecordVal &Val : R.getValues())2920if (Val.isNonconcreteOK() && !R.isTemplateArg(Val.getNameInit()))2921OS << Val;2922for (const RecordVal &Val : R.getValues())2923if (!Val.isNonconcreteOK() && !R.isTemplateArg(Val.getNameInit()))2924OS << Val;29252926return OS << "}\n";2927}29282929SMLoc Record::getFieldLoc(StringRef FieldName) const {2930const RecordVal *R = getValue(FieldName);2931if (!R)2932PrintFatalError(getLoc(), "Record `" + getName() +2933"' does not have a field named `" + FieldName + "'!\n");2934return R->getLoc();2935}29362937Init *Record::getValueInit(StringRef FieldName) const {2938const RecordVal *R = getValue(FieldName);2939if (!R || !R->getValue())2940PrintFatalError(getLoc(), "Record `" + getName() +2941"' does not have a field named `" + FieldName + "'!\n");2942return R->getValue();2943}29442945StringRef Record::getValueAsString(StringRef FieldName) const {2946std::optional<StringRef> S = getValueAsOptionalString(FieldName);2947if (!S)2948PrintFatalError(getLoc(), "Record `" + getName() +2949"' does not have a field named `" + FieldName + "'!\n");2950return *S;2951}29522953std::optional<StringRef>2954Record::getValueAsOptionalString(StringRef FieldName) const {2955const RecordVal *R = getValue(FieldName);2956if (!R || !R->getValue())2957return std::nullopt;2958if (isa<UnsetInit>(R->getValue()))2959return std::nullopt;29602961if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))2962return SI->getValue();29632964PrintFatalError(getLoc(),2965"Record `" + getName() + "', ` field `" + FieldName +2966"' exists but does not have a string initializer!");2967}29682969BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {2970const RecordVal *R = getValue(FieldName);2971if (!R || !R->getValue())2972PrintFatalError(getLoc(), "Record `" + getName() +2973"' does not have a field named `" + FieldName + "'!\n");29742975if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))2976return BI;2977PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +2978"' exists but does not have a bits value");2979}29802981ListInit *Record::getValueAsListInit(StringRef FieldName) const {2982const RecordVal *R = getValue(FieldName);2983if (!R || !R->getValue())2984PrintFatalError(getLoc(), "Record `" + getName() +2985"' does not have a field named `" + FieldName + "'!\n");29862987if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))2988return LI;2989PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +2990"' exists but does not have a list value");2991}29922993std::vector<Record*>2994Record::getValueAsListOfDefs(StringRef FieldName) const {2995ListInit *List = getValueAsListInit(FieldName);2996std::vector<Record*> Defs;2997for (Init *I : List->getValues()) {2998if (DefInit *DI = dyn_cast<DefInit>(I))2999Defs.push_back(DI->getDef());3000else3001PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +3002FieldName + "' list is not entirely DefInit!");3003}3004return Defs;3005}30063007int64_t Record::getValueAsInt(StringRef FieldName) const {3008const RecordVal *R = getValue(FieldName);3009if (!R || !R->getValue())3010PrintFatalError(getLoc(), "Record `" + getName() +3011"' does not have a field named `" + FieldName + "'!\n");30123013if (IntInit *II = dyn_cast<IntInit>(R->getValue()))3014return II->getValue();3015PrintFatalError(getLoc(), Twine("Record `") + getName() + "', field `" +3016FieldName +3017"' exists but does not have an int value: " +3018R->getValue()->getAsString());3019}30203021std::vector<int64_t>3022Record::getValueAsListOfInts(StringRef FieldName) const {3023ListInit *List = getValueAsListInit(FieldName);3024std::vector<int64_t> Ints;3025for (Init *I : List->getValues()) {3026if (IntInit *II = dyn_cast<IntInit>(I))3027Ints.push_back(II->getValue());3028else3029PrintFatalError(getLoc(),3030Twine("Record `") + getName() + "', field `" + FieldName +3031"' exists but does not have a list of ints value: " +3032I->getAsString());3033}3034return Ints;3035}30363037std::vector<StringRef>3038Record::getValueAsListOfStrings(StringRef FieldName) const {3039ListInit *List = getValueAsListInit(FieldName);3040std::vector<StringRef> Strings;3041for (Init *I : List->getValues()) {3042if (StringInit *SI = dyn_cast<StringInit>(I))3043Strings.push_back(SI->getValue());3044else3045PrintFatalError(getLoc(),3046Twine("Record `") + getName() + "', field `" + FieldName +3047"' exists but does not have a list of strings value: " +3048I->getAsString());3049}3050return Strings;3051}30523053Record *Record::getValueAsDef(StringRef FieldName) const {3054const RecordVal *R = getValue(FieldName);3055if (!R || !R->getValue())3056PrintFatalError(getLoc(), "Record `" + getName() +3057"' does not have a field named `" + FieldName + "'!\n");30583059if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))3060return DI->getDef();3061PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +3062FieldName + "' does not have a def initializer!");3063}30643065Record *Record::getValueAsOptionalDef(StringRef FieldName) const {3066const RecordVal *R = getValue(FieldName);3067if (!R || !R->getValue())3068PrintFatalError(getLoc(), "Record `" + getName() +3069"' does not have a field named `" + FieldName + "'!\n");30703071if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))3072return DI->getDef();3073if (isa<UnsetInit>(R->getValue()))3074return nullptr;3075PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +3076FieldName + "' does not have either a def initializer or '?'!");3077}307830793080bool Record::getValueAsBit(StringRef FieldName) const {3081const RecordVal *R = getValue(FieldName);3082if (!R || !R->getValue())3083PrintFatalError(getLoc(), "Record `" + getName() +3084"' does not have a field named `" + FieldName + "'!\n");30853086if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))3087return BI->getValue();3088PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +3089FieldName + "' does not have a bit initializer!");3090}30913092bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {3093const RecordVal *R = getValue(FieldName);3094if (!R || !R->getValue())3095PrintFatalError(getLoc(), "Record `" + getName() +3096"' does not have a field named `" + FieldName.str() + "'!\n");30973098if (isa<UnsetInit>(R->getValue())) {3099Unset = true;3100return false;3101}3102Unset = false;3103if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))3104return BI->getValue();3105PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +3106FieldName + "' does not have a bit initializer!");3107}31083109DagInit *Record::getValueAsDag(StringRef FieldName) const {3110const RecordVal *R = getValue(FieldName);3111if (!R || !R->getValue())3112PrintFatalError(getLoc(), "Record `" + getName() +3113"' does not have a field named `" + FieldName + "'!\n");31143115if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))3116return DI;3117PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +3118FieldName + "' does not have a dag initializer!");3119}31203121// Check all record assertions: For each one, resolve the condition3122// and message, then call CheckAssert().3123// Note: The condition and message are probably already resolved,3124// but resolving again allows calls before records are resolved.3125void Record::checkRecordAssertions() {3126RecordResolver R(*this);3127R.setFinal(true);31283129for (const auto &Assertion : getAssertions()) {3130Init *Condition = Assertion.Condition->resolveReferences(R);3131Init *Message = Assertion.Message->resolveReferences(R);3132CheckAssert(Assertion.Loc, Condition, Message);3133}3134}31353136void Record::emitRecordDumps() {3137RecordResolver R(*this);3138R.setFinal(true);31393140for (const auto &Dump : getDumps()) {3141Init *Message = Dump.Message->resolveReferences(R);3142dumpMessage(Dump.Loc, Message);3143}3144}31453146// Report a warning if the record has unused template arguments.3147void Record::checkUnusedTemplateArgs() {3148for (const Init *TA : getTemplateArgs()) {3149const RecordVal *Arg = getValue(TA);3150if (!Arg->isUsed())3151PrintWarning(Arg->getLoc(),3152"unused template argument: " + Twine(Arg->getName()));3153}3154}31553156RecordKeeper::RecordKeeper()3157: Impl(std::make_unique<detail::RecordKeeperImpl>(*this)) {}3158RecordKeeper::~RecordKeeper() = default;31593160#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)3161LLVM_DUMP_METHOD void RecordKeeper::dump() const { errs() << *this; }3162#endif31633164raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {3165OS << "------------- Classes -----------------\n";3166for (const auto &C : RK.getClasses())3167OS << "class " << *C.second;31683169OS << "------------- Defs -----------------\n";3170for (const auto &D : RK.getDefs())3171OS << "def " << *D.second;3172return OS;3173}31743175/// GetNewAnonymousName - Generate a unique anonymous name that can be used as3176/// an identifier.3177Init *RecordKeeper::getNewAnonymousName() {3178return AnonymousNameInit::get(*this, getImpl().AnonCounter++);3179}31803181// These functions implement the phase timing facility. Starting a timer3182// when one is already running stops the running one.31833184void RecordKeeper::startTimer(StringRef Name) {3185if (TimingGroup) {3186if (LastTimer && LastTimer->isRunning()) {3187LastTimer->stopTimer();3188if (BackendTimer) {3189LastTimer->clear();3190BackendTimer = false;3191}3192}31933194LastTimer = new Timer("", Name, *TimingGroup);3195LastTimer->startTimer();3196}3197}31983199void RecordKeeper::stopTimer() {3200if (TimingGroup) {3201assert(LastTimer && "No phase timer was started");3202LastTimer->stopTimer();3203}3204}32053206void RecordKeeper::startBackendTimer(StringRef Name) {3207if (TimingGroup) {3208startTimer(Name);3209BackendTimer = true;3210}3211}32123213void RecordKeeper::stopBackendTimer() {3214if (TimingGroup) {3215if (BackendTimer) {3216stopTimer();3217BackendTimer = false;3218}3219}3220}32213222std::vector<Record *>3223RecordKeeper::getAllDerivedDefinitions(StringRef ClassName) const {3224// We cache the record vectors for single classes. Many backends request3225// the same vectors multiple times.3226auto Pair = ClassRecordsMap.try_emplace(ClassName);3227if (Pair.second)3228Pair.first->second = getAllDerivedDefinitions(ArrayRef(ClassName));32293230return Pair.first->second;3231}32323233std::vector<Record *> RecordKeeper::getAllDerivedDefinitions(3234ArrayRef<StringRef> ClassNames) const {3235SmallVector<Record *, 2> ClassRecs;3236std::vector<Record *> Defs;32373238assert(ClassNames.size() > 0 && "At least one class must be passed.");3239for (const auto &ClassName : ClassNames) {3240Record *Class = getClass(ClassName);3241if (!Class)3242PrintFatalError("The class '" + ClassName + "' is not defined\n");3243ClassRecs.push_back(Class);3244}32453246for (const auto &OneDef : getDefs()) {3247if (all_of(ClassRecs, [&OneDef](const Record *Class) {3248return OneDef.second->isSubClassOf(Class);3249}))3250Defs.push_back(OneDef.second.get());3251}32523253llvm::sort(Defs, LessRecord());32543255return Defs;3256}32573258std::vector<Record *>3259RecordKeeper::getAllDerivedDefinitionsIfDefined(StringRef ClassName) const {3260return getClass(ClassName) ? getAllDerivedDefinitions(ClassName)3261: std::vector<Record *>();3262}32633264Init *MapResolver::resolve(Init *VarName) {3265auto It = Map.find(VarName);3266if (It == Map.end())3267return nullptr;32683269Init *I = It->second.V;32703271if (!It->second.Resolved && Map.size() > 1) {3272// Resolve mutual references among the mapped variables, but prevent3273// infinite recursion.3274Map.erase(It);3275I = I->resolveReferences(*this);3276Map[VarName] = {I, true};3277}32783279return I;3280}32813282Init *RecordResolver::resolve(Init *VarName) {3283Init *Val = Cache.lookup(VarName);3284if (Val)3285return Val;32863287if (llvm::is_contained(Stack, VarName))3288return nullptr; // prevent infinite recursion32893290if (RecordVal *RV = getCurrentRecord()->getValue(VarName)) {3291if (!isa<UnsetInit>(RV->getValue())) {3292Val = RV->getValue();3293Stack.push_back(VarName);3294Val = Val->resolveReferences(*this);3295Stack.pop_back();3296}3297} else if (Name && VarName == getCurrentRecord()->getNameInit()) {3298Stack.push_back(VarName);3299Val = Name->resolveReferences(*this);3300Stack.pop_back();3301}33023303Cache[VarName] = Val;3304return Val;3305}33063307Init *TrackUnresolvedResolver::resolve(Init *VarName) {3308Init *I = nullptr;33093310if (R) {3311I = R->resolve(VarName);3312if (I && !FoundUnresolved) {3313// Do not recurse into the resolved initializer, as that would change3314// the behavior of the resolver we're delegating, but do check to see3315// if there are unresolved variables remaining.3316TrackUnresolvedResolver Sub;3317I->resolveReferences(Sub);3318FoundUnresolved |= Sub.FoundUnresolved;3319}3320}33213322if (!I)3323FoundUnresolved = true;3324return I;3325}33263327Init *HasReferenceResolver::resolve(Init *VarName)3328{3329if (VarName == VarNameToTrack)3330Found = true;3331return nullptr;3332}333333343335