SetTheory.cpp 11 KB

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