Path: blob/main/contrib/llvm-project/llvm/lib/TableGen/SetTheory.cpp
35233 views
//===- SetTheory.cpp - Generate ordered sets from DAG expressions ---------===//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// This file implements the SetTheory class that computes ordered sets of9// Records from DAG expressions.10//11//===----------------------------------------------------------------------===//1213#include "llvm/TableGen/SetTheory.h"14#include "llvm/ADT/ArrayRef.h"15#include "llvm/ADT/SmallVector.h"16#include "llvm/ADT/StringRef.h"17#include "llvm/Support/Casting.h"18#include "llvm/Support/Format.h"19#include "llvm/Support/SMLoc.h"20#include "llvm/Support/raw_ostream.h"21#include "llvm/TableGen/Error.h"22#include "llvm/TableGen/Record.h"23#include <algorithm>24#include <cstdint>25#include <string>26#include <utility>2728using namespace llvm;2930// Define the standard operators.31namespace {3233using RecSet = SetTheory::RecSet;34using RecVec = SetTheory::RecVec;3536// (add a, b, ...) Evaluate and union all arguments.37struct AddOp : public SetTheory::Operator {38void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,39ArrayRef<SMLoc> Loc) override {40ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts, Loc);41}42};4344// (sub Add, Sub, ...) Set difference.45struct SubOp : public SetTheory::Operator {46void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,47ArrayRef<SMLoc> Loc) override {48if (Expr->arg_size() < 2)49PrintFatalError(Loc, "Set difference needs at least two arguments: " +50Expr->getAsString());51RecSet Add, Sub;52ST.evaluate(*Expr->arg_begin(), Add, Loc);53ST.evaluate(Expr->arg_begin() + 1, Expr->arg_end(), Sub, Loc);54for (const auto &I : Add)55if (!Sub.count(I))56Elts.insert(I);57}58};5960// (and S1, S2) Set intersection.61struct AndOp : public SetTheory::Operator {62void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,63ArrayRef<SMLoc> Loc) override {64if (Expr->arg_size() != 2)65PrintFatalError(Loc, "Set intersection requires two arguments: " +66Expr->getAsString());67RecSet S1, S2;68ST.evaluate(Expr->arg_begin()[0], S1, Loc);69ST.evaluate(Expr->arg_begin()[1], S2, Loc);70for (const auto &I : S1)71if (S2.count(I))72Elts.insert(I);73}74};7576// SetIntBinOp - Abstract base class for (Op S, N) operators.77struct SetIntBinOp : public SetTheory::Operator {78virtual void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,79RecSet &Elts, ArrayRef<SMLoc> Loc) = 0;8081void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,82ArrayRef<SMLoc> Loc) override {83if (Expr->arg_size() != 2)84PrintFatalError(Loc, "Operator requires (Op Set, Int) arguments: " +85Expr->getAsString());86RecSet Set;87ST.evaluate(Expr->arg_begin()[0], Set, Loc);88IntInit *II = dyn_cast<IntInit>(Expr->arg_begin()[1]);89if (!II)90PrintFatalError(Loc, "Second argument must be an integer: " +91Expr->getAsString());92apply2(ST, Expr, Set, II->getValue(), Elts, Loc);93}94};9596// (shl S, N) Shift left, remove the first N elements.97struct ShlOp : public SetIntBinOp {98void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,99RecSet &Elts, ArrayRef<SMLoc> Loc) override {100if (N < 0)101PrintFatalError(Loc, "Positive shift required: " +102Expr->getAsString());103if (unsigned(N) < Set.size())104Elts.insert(Set.begin() + N, Set.end());105}106};107108// (trunc S, N) Truncate after the first N elements.109struct TruncOp : public SetIntBinOp {110void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,111RecSet &Elts, ArrayRef<SMLoc> Loc) override {112if (N < 0)113PrintFatalError(Loc, "Positive length required: " +114Expr->getAsString());115if (unsigned(N) > Set.size())116N = Set.size();117Elts.insert(Set.begin(), Set.begin() + N);118}119};120121// Left/right rotation.122struct RotOp : public SetIntBinOp {123const bool Reverse;124125RotOp(bool Rev) : Reverse(Rev) {}126127void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,128RecSet &Elts, ArrayRef<SMLoc> Loc) override {129if (Reverse)130N = -N;131// N > 0 -> rotate left, N < 0 -> rotate right.132if (Set.empty())133return;134if (N < 0)135N = Set.size() - (-N % Set.size());136else137N %= Set.size();138Elts.insert(Set.begin() + N, Set.end());139Elts.insert(Set.begin(), Set.begin() + N);140}141};142143// (decimate S, N) Pick every N'th element of S.144struct DecimateOp : public SetIntBinOp {145void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,146RecSet &Elts, ArrayRef<SMLoc> Loc) override {147if (N <= 0)148PrintFatalError(Loc, "Positive stride required: " +149Expr->getAsString());150for (unsigned I = 0; I < Set.size(); I += N)151Elts.insert(Set[I]);152}153};154155// (interleave S1, S2, ...) Interleave elements of the arguments.156struct InterleaveOp : public SetTheory::Operator {157void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,158ArrayRef<SMLoc> Loc) override {159// Evaluate the arguments individually.160SmallVector<RecSet, 4> Args(Expr->getNumArgs());161unsigned MaxSize = 0;162for (unsigned i = 0, e = Expr->getNumArgs(); i != e; ++i) {163ST.evaluate(Expr->getArg(i), Args[i], Loc);164MaxSize = std::max(MaxSize, unsigned(Args[i].size()));165}166// Interleave arguments into Elts.167for (unsigned n = 0; n != MaxSize; ++n)168for (unsigned i = 0, e = Expr->getNumArgs(); i != e; ++i)169if (n < Args[i].size())170Elts.insert(Args[i][n]);171}172};173174// (sequence "Format", From, To) Generate a sequence of records by name.175struct SequenceOp : public SetTheory::Operator {176void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,177ArrayRef<SMLoc> Loc) override {178int Step = 1;179if (Expr->arg_size() > 4)180PrintFatalError(Loc, "Bad args to (sequence \"Format\", From, To): " +181Expr->getAsString());182else if (Expr->arg_size() == 4) {183if (IntInit *II = dyn_cast<IntInit>(Expr->arg_begin()[3])) {184Step = II->getValue();185} else186PrintFatalError(Loc, "Stride must be an integer: " +187Expr->getAsString());188}189190std::string Format;191if (StringInit *SI = dyn_cast<StringInit>(Expr->arg_begin()[0]))192Format = std::string(SI->getValue());193else194PrintFatalError(Loc, "Format must be a string: " + Expr->getAsString());195196int64_t From, To;197if (IntInit *II = dyn_cast<IntInit>(Expr->arg_begin()[1]))198From = II->getValue();199else200PrintFatalError(Loc, "From must be an integer: " + Expr->getAsString());201if (From < 0 || From >= (1 << 30))202PrintFatalError(Loc, "From out of range");203204if (IntInit *II = dyn_cast<IntInit>(Expr->arg_begin()[2]))205To = II->getValue();206else207PrintFatalError(Loc, "To must be an integer: " + Expr->getAsString());208if (To < 0 || To >= (1 << 30))209PrintFatalError(Loc, "To out of range");210211RecordKeeper &Records =212cast<DefInit>(Expr->getOperator())->getDef()->getRecords();213214Step *= From <= To ? 1 : -1;215while (true) {216if (Step > 0 && From > To)217break;218else if (Step < 0 && From < To)219break;220std::string Name;221raw_string_ostream OS(Name);222OS << format(Format.c_str(), unsigned(From));223Record *Rec = Records.getDef(Name);224if (!Rec)225PrintFatalError(Loc, "No def named '" + Name + "': " +226Expr->getAsString());227// Try to reevaluate Rec in case it is a set.228if (const RecVec *Result = ST.expand(Rec))229Elts.insert(Result->begin(), Result->end());230else231Elts.insert(Rec);232233From += Step;234}235}236};237238// Expand a Def into a set by evaluating one of its fields.239struct FieldExpander : public SetTheory::Expander {240StringRef FieldName;241242FieldExpander(StringRef fn) : FieldName(fn) {}243244void expand(SetTheory &ST, Record *Def, RecSet &Elts) override {245ST.evaluate(Def->getValueInit(FieldName), Elts, Def->getLoc());246}247};248249} // end anonymous namespace250251// Pin the vtables to this file.252void SetTheory::Operator::anchor() {}253void SetTheory::Expander::anchor() {}254255SetTheory::SetTheory() {256addOperator("add", std::make_unique<AddOp>());257addOperator("sub", std::make_unique<SubOp>());258addOperator("and", std::make_unique<AndOp>());259addOperator("shl", std::make_unique<ShlOp>());260addOperator("trunc", std::make_unique<TruncOp>());261addOperator("rotl", std::make_unique<RotOp>(false));262addOperator("rotr", std::make_unique<RotOp>(true));263addOperator("decimate", std::make_unique<DecimateOp>());264addOperator("interleave", std::make_unique<InterleaveOp>());265addOperator("sequence", std::make_unique<SequenceOp>());266}267268void SetTheory::addOperator(StringRef Name, std::unique_ptr<Operator> Op) {269Operators[Name] = std::move(Op);270}271272void SetTheory::addExpander(StringRef ClassName, std::unique_ptr<Expander> E) {273Expanders[ClassName] = std::move(E);274}275276void SetTheory::addFieldExpander(StringRef ClassName, StringRef FieldName) {277addExpander(ClassName, std::make_unique<FieldExpander>(FieldName));278}279280void SetTheory::evaluate(Init *Expr, RecSet &Elts, ArrayRef<SMLoc> Loc) {281// A def in a list can be a just an element, or it may expand.282if (DefInit *Def = dyn_cast<DefInit>(Expr)) {283if (const RecVec *Result = expand(Def->getDef()))284return Elts.insert(Result->begin(), Result->end());285Elts.insert(Def->getDef());286return;287}288289// Lists simply expand.290if (ListInit *LI = dyn_cast<ListInit>(Expr))291return evaluate(LI->begin(), LI->end(), Elts, Loc);292293// Anything else must be a DAG.294DagInit *DagExpr = dyn_cast<DagInit>(Expr);295if (!DagExpr)296PrintFatalError(Loc, "Invalid set element: " + Expr->getAsString());297DefInit *OpInit = dyn_cast<DefInit>(DagExpr->getOperator());298if (!OpInit)299PrintFatalError(Loc, "Bad set expression: " + Expr->getAsString());300auto I = Operators.find(OpInit->getDef()->getName());301if (I == Operators.end())302PrintFatalError(Loc, "Unknown set operator: " + Expr->getAsString());303I->second->apply(*this, DagExpr, Elts, Loc);304}305306const RecVec *SetTheory::expand(Record *Set) {307// Check existing entries for Set and return early.308ExpandMap::iterator I = Expansions.find(Set);309if (I != Expansions.end())310return &I->second;311312// This is the first time we see Set. Find a suitable expander.313ArrayRef<std::pair<Record *, SMRange>> SC = Set->getSuperClasses();314for (const auto &SCPair : SC) {315// Skip unnamed superclasses.316if (!isa<StringInit>(SCPair.first->getNameInit()))317continue;318auto I = Expanders.find(SCPair.first->getName());319if (I != Expanders.end()) {320// This breaks recursive definitions.321RecVec &EltVec = Expansions[Set];322RecSet Elts;323I->second->expand(*this, Set, Elts);324EltVec.assign(Elts.begin(), Elts.end());325return &EltVec;326}327}328329// Set is not expandable.330return nullptr;331}332333334