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