1f1653b52SJames Molloy //===- SetTheory.cpp - Generate ordered sets from DAG expressions ---------===//
2f1653b52SJames Molloy //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6f1653b52SJames Molloy //
7f1653b52SJames Molloy //===----------------------------------------------------------------------===//
8f1653b52SJames Molloy //
9f1653b52SJames Molloy // This file implements the SetTheory class that computes ordered sets of
10f1653b52SJames Molloy // Records from DAG expressions.
11f1653b52SJames Molloy //
12f1653b52SJames Molloy //===----------------------------------------------------------------------===//
13f1653b52SJames Molloy 
14*92f49b89Sserge-sans-paille #include "llvm/TableGen/SetTheory.h"
15af615896SEugene Zelenko #include "llvm/ADT/ArrayRef.h"
16af615896SEugene Zelenko #include "llvm/ADT/SmallVector.h"
17af615896SEugene Zelenko #include "llvm/ADT/StringRef.h"
18af615896SEugene Zelenko #include "llvm/Support/Casting.h"
19f1653b52SJames Molloy #include "llvm/Support/Format.h"
20af615896SEugene Zelenko #include "llvm/Support/SMLoc.h"
21af615896SEugene Zelenko #include "llvm/Support/raw_ostream.h"
22f1653b52SJames Molloy #include "llvm/TableGen/Error.h"
23f1653b52SJames Molloy #include "llvm/TableGen/Record.h"
24af615896SEugene Zelenko #include <algorithm>
25af615896SEugene Zelenko #include <cstdint>
26af615896SEugene Zelenko #include <string>
27af615896SEugene Zelenko #include <utility>
28f1653b52SJames Molloy 
29f1653b52SJames Molloy using namespace llvm;
30f1653b52SJames Molloy 
31f1653b52SJames Molloy // Define the standard operators.
32f1653b52SJames Molloy namespace {
33f1653b52SJames Molloy 
34af615896SEugene Zelenko using RecSet = SetTheory::RecSet;
35af615896SEugene Zelenko using RecVec = SetTheory::RecVec;
36f1653b52SJames Molloy 
37f1653b52SJames Molloy // (add a, b, ...) Evaluate and union all arguments.
38f1653b52SJames Molloy struct AddOp : public SetTheory::Operator {
apply__anon8d82ef980111::AddOp39f1653b52SJames Molloy   void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,
40f1653b52SJames Molloy              ArrayRef<SMLoc> Loc) override {
41f1653b52SJames Molloy     ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts, Loc);
42f1653b52SJames Molloy   }
43f1653b52SJames Molloy };
44f1653b52SJames Molloy 
45f1653b52SJames Molloy // (sub Add, Sub, ...) Set difference.
46f1653b52SJames Molloy struct SubOp : public SetTheory::Operator {
apply__anon8d82ef980111::SubOp47f1653b52SJames Molloy   void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,
48f1653b52SJames Molloy              ArrayRef<SMLoc> Loc) override {
49f1653b52SJames Molloy     if (Expr->arg_size() < 2)
50f1653b52SJames Molloy       PrintFatalError(Loc, "Set difference needs at least two arguments: " +
51f1653b52SJames Molloy         Expr->getAsString());
52f1653b52SJames Molloy     RecSet Add, Sub;
53f1653b52SJames Molloy     ST.evaluate(*Expr->arg_begin(), Add, Loc);
54f1653b52SJames Molloy     ST.evaluate(Expr->arg_begin() + 1, Expr->arg_end(), Sub, Loc);
55dd9a6411SKazu Hirata     for (const auto &I : Add)
56dd9a6411SKazu Hirata       if (!Sub.count(I))
57dd9a6411SKazu Hirata         Elts.insert(I);
58f1653b52SJames Molloy   }
59f1653b52SJames Molloy };
60f1653b52SJames Molloy 
61f1653b52SJames Molloy // (and S1, S2) Set intersection.
62f1653b52SJames Molloy struct AndOp : public SetTheory::Operator {
apply__anon8d82ef980111::AndOp63f1653b52SJames Molloy   void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,
64f1653b52SJames Molloy              ArrayRef<SMLoc> Loc) override {
65f1653b52SJames Molloy     if (Expr->arg_size() != 2)
66f1653b52SJames Molloy       PrintFatalError(Loc, "Set intersection requires two arguments: " +
67f1653b52SJames Molloy         Expr->getAsString());
68f1653b52SJames Molloy     RecSet S1, S2;
69f1653b52SJames Molloy     ST.evaluate(Expr->arg_begin()[0], S1, Loc);
70f1653b52SJames Molloy     ST.evaluate(Expr->arg_begin()[1], S2, Loc);
71dd9a6411SKazu Hirata     for (const auto &I : S1)
72dd9a6411SKazu Hirata       if (S2.count(I))
73dd9a6411SKazu Hirata         Elts.insert(I);
74f1653b52SJames Molloy   }
75f1653b52SJames Molloy };
76f1653b52SJames Molloy 
77f1653b52SJames Molloy // SetIntBinOp - Abstract base class for (Op S, N) operators.
78f1653b52SJames Molloy struct SetIntBinOp : public SetTheory::Operator {
79f1653b52SJames Molloy   virtual void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,
80f1653b52SJames Molloy                       RecSet &Elts, ArrayRef<SMLoc> Loc) = 0;
81f1653b52SJames Molloy 
apply__anon8d82ef980111::SetIntBinOp82f1653b52SJames Molloy   void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,
83f1653b52SJames Molloy              ArrayRef<SMLoc> Loc) override {
84f1653b52SJames Molloy     if (Expr->arg_size() != 2)
85f1653b52SJames Molloy       PrintFatalError(Loc, "Operator requires (Op Set, Int) arguments: " +
86f1653b52SJames Molloy         Expr->getAsString());
87f1653b52SJames Molloy     RecSet Set;
88f1653b52SJames Molloy     ST.evaluate(Expr->arg_begin()[0], Set, Loc);
89f1653b52SJames Molloy     IntInit *II = dyn_cast<IntInit>(Expr->arg_begin()[1]);
90f1653b52SJames Molloy     if (!II)
91f1653b52SJames Molloy       PrintFatalError(Loc, "Second argument must be an integer: " +
92f1653b52SJames Molloy         Expr->getAsString());
93f1653b52SJames Molloy     apply2(ST, Expr, Set, II->getValue(), Elts, Loc);
94f1653b52SJames Molloy   }
95f1653b52SJames Molloy };
96f1653b52SJames Molloy 
97f1653b52SJames Molloy // (shl S, N) Shift left, remove the first N elements.
98f1653b52SJames Molloy struct ShlOp : public SetIntBinOp {
apply2__anon8d82ef980111::ShlOp99f1653b52SJames Molloy   void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,
100f1653b52SJames Molloy               RecSet &Elts, ArrayRef<SMLoc> Loc) override {
101f1653b52SJames Molloy     if (N < 0)
102f1653b52SJames Molloy       PrintFatalError(Loc, "Positive shift required: " +
103f1653b52SJames Molloy         Expr->getAsString());
104f1653b52SJames Molloy     if (unsigned(N) < Set.size())
105f1653b52SJames Molloy       Elts.insert(Set.begin() + N, Set.end());
106f1653b52SJames Molloy   }
107f1653b52SJames Molloy };
108f1653b52SJames Molloy 
109f1653b52SJames Molloy // (trunc S, N) Truncate after the first N elements.
110f1653b52SJames Molloy struct TruncOp : public SetIntBinOp {
apply2__anon8d82ef980111::TruncOp111f1653b52SJames Molloy   void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,
112f1653b52SJames Molloy               RecSet &Elts, ArrayRef<SMLoc> Loc) override {
113f1653b52SJames Molloy     if (N < 0)
114f1653b52SJames Molloy       PrintFatalError(Loc, "Positive length required: " +
115f1653b52SJames Molloy         Expr->getAsString());
116f1653b52SJames Molloy     if (unsigned(N) > Set.size())
117f1653b52SJames Molloy       N = Set.size();
118f1653b52SJames Molloy     Elts.insert(Set.begin(), Set.begin() + N);
119f1653b52SJames Molloy   }
120f1653b52SJames Molloy };
121f1653b52SJames Molloy 
122f1653b52SJames Molloy // Left/right rotation.
123f1653b52SJames Molloy struct RotOp : public SetIntBinOp {
124f1653b52SJames Molloy   const bool Reverse;
125f1653b52SJames Molloy 
RotOp__anon8d82ef980111::RotOp126f1653b52SJames Molloy   RotOp(bool Rev) : Reverse(Rev) {}
127f1653b52SJames Molloy 
apply2__anon8d82ef980111::RotOp128f1653b52SJames Molloy   void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,
129f1653b52SJames Molloy               RecSet &Elts, ArrayRef<SMLoc> Loc) override {
130f1653b52SJames Molloy     if (Reverse)
131f1653b52SJames Molloy       N = -N;
132f1653b52SJames Molloy     // N > 0 -> rotate left, N < 0 -> rotate right.
133f1653b52SJames Molloy     if (Set.empty())
134f1653b52SJames Molloy       return;
135f1653b52SJames Molloy     if (N < 0)
136f1653b52SJames Molloy       N = Set.size() - (-N % Set.size());
137f1653b52SJames Molloy     else
138f1653b52SJames Molloy       N %= Set.size();
139f1653b52SJames Molloy     Elts.insert(Set.begin() + N, Set.end());
140f1653b52SJames Molloy     Elts.insert(Set.begin(), Set.begin() + N);
141f1653b52SJames Molloy   }
142f1653b52SJames Molloy };
143f1653b52SJames Molloy 
144f1653b52SJames Molloy // (decimate S, N) Pick every N'th element of S.
145f1653b52SJames Molloy struct DecimateOp : public SetIntBinOp {
apply2__anon8d82ef980111::DecimateOp146f1653b52SJames Molloy   void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,
147f1653b52SJames Molloy               RecSet &Elts, ArrayRef<SMLoc> Loc) override {
148f1653b52SJames Molloy     if (N <= 0)
149f1653b52SJames Molloy       PrintFatalError(Loc, "Positive stride required: " +
150f1653b52SJames Molloy         Expr->getAsString());
151f1653b52SJames Molloy     for (unsigned I = 0; I < Set.size(); I += N)
152f1653b52SJames Molloy       Elts.insert(Set[I]);
153f1653b52SJames Molloy   }
154f1653b52SJames Molloy };
155f1653b52SJames Molloy 
156f1653b52SJames Molloy // (interleave S1, S2, ...) Interleave elements of the arguments.
157f1653b52SJames Molloy struct InterleaveOp : public SetTheory::Operator {
apply__anon8d82ef980111::InterleaveOp158f1653b52SJames Molloy   void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,
159f1653b52SJames Molloy              ArrayRef<SMLoc> Loc) override {
160f1653b52SJames Molloy     // Evaluate the arguments individually.
161f1653b52SJames Molloy     SmallVector<RecSet, 4> Args(Expr->getNumArgs());
162f1653b52SJames Molloy     unsigned MaxSize = 0;
163f1653b52SJames Molloy     for (unsigned i = 0, e = Expr->getNumArgs(); i != e; ++i) {
164f1653b52SJames Molloy       ST.evaluate(Expr->getArg(i), Args[i], Loc);
165f1653b52SJames Molloy       MaxSize = std::max(MaxSize, unsigned(Args[i].size()));
166f1653b52SJames Molloy     }
167f1653b52SJames Molloy     // Interleave arguments into Elts.
168f1653b52SJames Molloy     for (unsigned n = 0; n != MaxSize; ++n)
169f1653b52SJames Molloy       for (unsigned i = 0, e = Expr->getNumArgs(); i != e; ++i)
170f1653b52SJames Molloy         if (n < Args[i].size())
171f1653b52SJames Molloy           Elts.insert(Args[i][n]);
172f1653b52SJames Molloy   }
173f1653b52SJames Molloy };
174f1653b52SJames Molloy 
175f1653b52SJames Molloy // (sequence "Format", From, To) Generate a sequence of records by name.
176f1653b52SJames Molloy struct SequenceOp : public SetTheory::Operator {
apply__anon8d82ef980111::SequenceOp177f1653b52SJames Molloy   void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,
178f1653b52SJames Molloy              ArrayRef<SMLoc> Loc) override {
179f1653b52SJames Molloy     int Step = 1;
180f1653b52SJames Molloy     if (Expr->arg_size() > 4)
181f1653b52SJames Molloy       PrintFatalError(Loc, "Bad args to (sequence \"Format\", From, To): " +
182f1653b52SJames Molloy         Expr->getAsString());
183f1653b52SJames Molloy     else if (Expr->arg_size() == 4) {
184f1653b52SJames Molloy       if (IntInit *II = dyn_cast<IntInit>(Expr->arg_begin()[3])) {
185f1653b52SJames Molloy         Step = II->getValue();
186f1653b52SJames Molloy       } else
187f1653b52SJames Molloy         PrintFatalError(Loc, "Stride must be an integer: " +
188f1653b52SJames Molloy           Expr->getAsString());
189f1653b52SJames Molloy     }
190f1653b52SJames Molloy 
191f1653b52SJames Molloy     std::string Format;
192f1653b52SJames Molloy     if (StringInit *SI = dyn_cast<StringInit>(Expr->arg_begin()[0]))
193adcd0268SBenjamin Kramer       Format = std::string(SI->getValue());
194f1653b52SJames Molloy     else
195f1653b52SJames Molloy       PrintFatalError(Loc,  "Format must be a string: " + Expr->getAsString());
196f1653b52SJames Molloy 
197f1653b52SJames Molloy     int64_t From, To;
198f1653b52SJames Molloy     if (IntInit *II = dyn_cast<IntInit>(Expr->arg_begin()[1]))
199f1653b52SJames Molloy       From = II->getValue();
200f1653b52SJames Molloy     else
201f1653b52SJames Molloy       PrintFatalError(Loc, "From must be an integer: " + Expr->getAsString());
202f1653b52SJames Molloy     if (From < 0 || From >= (1 << 30))
203f1653b52SJames Molloy       PrintFatalError(Loc, "From out of range");
204f1653b52SJames Molloy 
205f1653b52SJames Molloy     if (IntInit *II = dyn_cast<IntInit>(Expr->arg_begin()[2]))
206f1653b52SJames Molloy       To = II->getValue();
207f1653b52SJames Molloy     else
208fa04402eSDavide Italiano       PrintFatalError(Loc, "To must be an integer: " + Expr->getAsString());
209f1653b52SJames Molloy     if (To < 0 || To >= (1 << 30))
210f1653b52SJames Molloy       PrintFatalError(Loc, "To out of range");
211f1653b52SJames Molloy 
212f1653b52SJames Molloy     RecordKeeper &Records =
213f1653b52SJames Molloy       cast<DefInit>(Expr->getOperator())->getDef()->getRecords();
214f1653b52SJames Molloy 
215f1653b52SJames Molloy     Step *= From <= To ? 1 : -1;
216f1653b52SJames Molloy     while (true) {
217f1653b52SJames Molloy       if (Step > 0 && From > To)
218f1653b52SJames Molloy         break;
219f1653b52SJames Molloy       else if (Step < 0 && From < To)
220f1653b52SJames Molloy         break;
221e69170a1SAlp Toker       std::string Name;
222e69170a1SAlp Toker       raw_string_ostream OS(Name);
223e69170a1SAlp Toker       OS << format(Format.c_str(), unsigned(From));
224e69170a1SAlp Toker       Record *Rec = Records.getDef(OS.str());
225f1653b52SJames Molloy       if (!Rec)
226e69170a1SAlp Toker         PrintFatalError(Loc, "No def named '" + Name + "': " +
227f1653b52SJames Molloy           Expr->getAsString());
228f1653b52SJames Molloy       // Try to reevaluate Rec in case it is a set.
229f1653b52SJames Molloy       if (const RecVec *Result = ST.expand(Rec))
230f1653b52SJames Molloy         Elts.insert(Result->begin(), Result->end());
231f1653b52SJames Molloy       else
232f1653b52SJames Molloy         Elts.insert(Rec);
233f1653b52SJames Molloy 
234f1653b52SJames Molloy       From += Step;
235f1653b52SJames Molloy     }
236f1653b52SJames Molloy   }
237f1653b52SJames Molloy };
238f1653b52SJames Molloy 
239f1653b52SJames Molloy // Expand a Def into a set by evaluating one of its fields.
240f1653b52SJames Molloy struct FieldExpander : public SetTheory::Expander {
241f1653b52SJames Molloy   StringRef FieldName;
242f1653b52SJames Molloy 
FieldExpander__anon8d82ef980111::FieldExpander243f1653b52SJames Molloy   FieldExpander(StringRef fn) : FieldName(fn) {}
244f1653b52SJames Molloy 
expand__anon8d82ef980111::FieldExpander245f1653b52SJames Molloy   void expand(SetTheory &ST, Record *Def, RecSet &Elts) override {
246f1653b52SJames Molloy     ST.evaluate(Def->getValueInit(FieldName), Elts, Def->getLoc());
247f1653b52SJames Molloy   }
248f1653b52SJames Molloy };
249af615896SEugene Zelenko 
250f1653b52SJames Molloy } // end anonymous namespace
251f1653b52SJames Molloy 
252f1653b52SJames Molloy // Pin the vtables to this file.
anchor()253f1653b52SJames Molloy void SetTheory::Operator::anchor() {}
anchor()254f1653b52SJames Molloy void SetTheory::Expander::anchor() {}
255f1653b52SJames Molloy 
SetTheory()256f1653b52SJames Molloy SetTheory::SetTheory() {
2570eaee545SJonas Devlieghere   addOperator("add", std::make_unique<AddOp>());
2580eaee545SJonas Devlieghere   addOperator("sub", std::make_unique<SubOp>());
2590eaee545SJonas Devlieghere   addOperator("and", std::make_unique<AndOp>());
2600eaee545SJonas Devlieghere   addOperator("shl", std::make_unique<ShlOp>());
2610eaee545SJonas Devlieghere   addOperator("trunc", std::make_unique<TruncOp>());
2620eaee545SJonas Devlieghere   addOperator("rotl", std::make_unique<RotOp>(false));
2630eaee545SJonas Devlieghere   addOperator("rotr", std::make_unique<RotOp>(true));
2640eaee545SJonas Devlieghere   addOperator("decimate", std::make_unique<DecimateOp>());
2650eaee545SJonas Devlieghere   addOperator("interleave", std::make_unique<InterleaveOp>());
2660eaee545SJonas Devlieghere   addOperator("sequence", std::make_unique<SequenceOp>());
267f1653b52SJames Molloy }
268f1653b52SJames Molloy 
addOperator(StringRef Name,std::unique_ptr<Operator> Op)269ba6057deSCraig Topper void SetTheory::addOperator(StringRef Name, std::unique_ptr<Operator> Op) {
270ba6057deSCraig Topper   Operators[Name] = std::move(Op);
271f1653b52SJames Molloy }
272f1653b52SJames Molloy 
addExpander(StringRef ClassName,std::unique_ptr<Expander> E)273ba6057deSCraig Topper void SetTheory::addExpander(StringRef ClassName, std::unique_ptr<Expander> E) {
274ba6057deSCraig Topper   Expanders[ClassName] = std::move(E);
275f1653b52SJames Molloy }
276f1653b52SJames Molloy 
addFieldExpander(StringRef ClassName,StringRef FieldName)277f1653b52SJames Molloy void SetTheory::addFieldExpander(StringRef ClassName, StringRef FieldName) {
2780eaee545SJonas Devlieghere   addExpander(ClassName, std::make_unique<FieldExpander>(FieldName));
279f1653b52SJames Molloy }
280f1653b52SJames Molloy 
evaluate(Init * Expr,RecSet & Elts,ArrayRef<SMLoc> Loc)281f1653b52SJames Molloy void SetTheory::evaluate(Init *Expr, RecSet &Elts, ArrayRef<SMLoc> Loc) {
282f1653b52SJames Molloy   // A def in a list can be a just an element, or it may expand.
283f1653b52SJames Molloy   if (DefInit *Def = dyn_cast<DefInit>(Expr)) {
284f1653b52SJames Molloy     if (const RecVec *Result = expand(Def->getDef()))
285f1653b52SJames Molloy       return Elts.insert(Result->begin(), Result->end());
286f1653b52SJames Molloy     Elts.insert(Def->getDef());
287f1653b52SJames Molloy     return;
288f1653b52SJames Molloy   }
289f1653b52SJames Molloy 
290f1653b52SJames Molloy   // Lists simply expand.
291f1653b52SJames Molloy   if (ListInit *LI = dyn_cast<ListInit>(Expr))
292f1653b52SJames Molloy     return evaluate(LI->begin(), LI->end(), Elts, Loc);
293f1653b52SJames Molloy 
294f1653b52SJames Molloy   // Anything else must be a DAG.
295f1653b52SJames Molloy   DagInit *DagExpr = dyn_cast<DagInit>(Expr);
296f1653b52SJames Molloy   if (!DagExpr)
297f1653b52SJames Molloy     PrintFatalError(Loc, "Invalid set element: " + Expr->getAsString());
298f1653b52SJames Molloy   DefInit *OpInit = dyn_cast<DefInit>(DagExpr->getOperator());
299f1653b52SJames Molloy   if (!OpInit)
300f1653b52SJames Molloy     PrintFatalError(Loc, "Bad set expression: " + Expr->getAsString());
301ba6057deSCraig Topper   auto I = Operators.find(OpInit->getDef()->getName());
302ba6057deSCraig Topper   if (I == Operators.end())
303f1653b52SJames Molloy     PrintFatalError(Loc, "Unknown set operator: " + Expr->getAsString());
304ba6057deSCraig Topper   I->second->apply(*this, DagExpr, Elts, Loc);
305f1653b52SJames Molloy }
306f1653b52SJames Molloy 
expand(Record * Set)307f1653b52SJames Molloy const RecVec *SetTheory::expand(Record *Set) {
308f1653b52SJames Molloy   // Check existing entries for Set and return early.
309f1653b52SJames Molloy   ExpandMap::iterator I = Expansions.find(Set);
310f1653b52SJames Molloy   if (I != Expansions.end())
311f1653b52SJames Molloy     return &I->second;
312f1653b52SJames Molloy 
313f1653b52SJames Molloy   // This is the first time we see Set. Find a suitable expander.
3140e41d0b9SCraig Topper   ArrayRef<std::pair<Record *, SMRange>> SC = Set->getSuperClasses();
3150e41d0b9SCraig Topper   for (const auto &SCPair : SC) {
316f1653b52SJames Molloy     // Skip unnamed superclasses.
3170e41d0b9SCraig Topper     if (!isa<StringInit>(SCPair.first->getNameInit()))
318f1653b52SJames Molloy       continue;
3190e41d0b9SCraig Topper     auto I = Expanders.find(SCPair.first->getName());
320ba6057deSCraig Topper     if (I != Expanders.end()) {
321f1653b52SJames Molloy       // This breaks recursive definitions.
322f1653b52SJames Molloy       RecVec &EltVec = Expansions[Set];
323f1653b52SJames Molloy       RecSet Elts;
324ba6057deSCraig Topper       I->second->expand(*this, Set, Elts);
325f1653b52SJames Molloy       EltVec.assign(Elts.begin(), Elts.end());
326f1653b52SJames Molloy       return &EltVec;
327f1653b52SJames Molloy     }
328f1653b52SJames Molloy   }
329f1653b52SJames Molloy 
330f1653b52SJames Molloy   // Set is not expandable.
331f1653b52SJames Molloy   return nullptr;
332f1653b52SJames Molloy }
333