• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/TableGen/Error.h"
17 #include "llvm/TableGen/Record.h"
18 #include "llvm/Support/Format.h"
19 
20 using namespace llvm;
21 
22 // Define the standard operators.
23 namespace {
24 
25 typedef SetTheory::RecSet RecSet;
26 typedef SetTheory::RecVec RecVec;
27 
28 // (add a, b, ...) Evaluate and union all arguments.
29 struct AddOp : public SetTheory::Operator {
apply__anone0c51e680111::AddOp30   void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts) {
31     ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts);
32   }
33 };
34 
35 // (sub Add, Sub, ...) Set difference.
36 struct SubOp : public SetTheory::Operator {
apply__anone0c51e680111::SubOp37   void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts) {
38     if (Expr->arg_size() < 2)
39       throw "Set difference needs at least two arguments: " +
40         Expr->getAsString();
41     RecSet Add, Sub;
42     ST.evaluate(*Expr->arg_begin(), Add);
43     ST.evaluate(Expr->arg_begin() + 1, Expr->arg_end(), Sub);
44     for (RecSet::iterator I = Add.begin(), E = Add.end(); I != E; ++I)
45       if (!Sub.count(*I))
46         Elts.insert(*I);
47   }
48 };
49 
50 // (and S1, S2) Set intersection.
51 struct AndOp : public SetTheory::Operator {
apply__anone0c51e680111::AndOp52   void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts) {
53     if (Expr->arg_size() != 2)
54       throw "Set intersection requires two arguments: " + Expr->getAsString();
55     RecSet S1, S2;
56     ST.evaluate(Expr->arg_begin()[0], S1);
57     ST.evaluate(Expr->arg_begin()[1], S2);
58     for (RecSet::iterator I = S1.begin(), E = S1.end(); I != E; ++I)
59       if (S2.count(*I))
60         Elts.insert(*I);
61   }
62 };
63 
64 // SetIntBinOp - Abstract base class for (Op S, N) operators.
65 struct SetIntBinOp : public SetTheory::Operator {
66   virtual void apply2(SetTheory &ST, DagInit *Expr,
67                      RecSet &Set, int64_t N,
68                      RecSet &Elts) =0;
69 
apply__anone0c51e680111::SetIntBinOp70   void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts) {
71     if (Expr->arg_size() != 2)
72       throw "Operator requires (Op Set, Int) arguments: " + Expr->getAsString();
73     RecSet Set;
74     ST.evaluate(Expr->arg_begin()[0], Set);
75     IntInit *II = dynamic_cast<IntInit*>(Expr->arg_begin()[1]);
76     if (!II)
77       throw "Second argument must be an integer: " + Expr->getAsString();
78     apply2(ST, Expr, Set, II->getValue(), Elts);
79   }
80 };
81 
82 // (shl S, N) Shift left, remove the first N elements.
83 struct ShlOp : public SetIntBinOp {
apply2__anone0c51e680111::ShlOp84   void apply2(SetTheory &ST, DagInit *Expr,
85              RecSet &Set, int64_t N,
86              RecSet &Elts) {
87     if (N < 0)
88       throw "Positive shift required: " + Expr->getAsString();
89     if (unsigned(N) < Set.size())
90       Elts.insert(Set.begin() + N, Set.end());
91   }
92 };
93 
94 // (trunc S, N) Truncate after the first N elements.
95 struct TruncOp : public SetIntBinOp {
apply2__anone0c51e680111::TruncOp96   void apply2(SetTheory &ST, DagInit *Expr,
97              RecSet &Set, int64_t N,
98              RecSet &Elts) {
99     if (N < 0)
100       throw "Positive length required: " + Expr->getAsString();
101     if (unsigned(N) > Set.size())
102       N = Set.size();
103     Elts.insert(Set.begin(), Set.begin() + N);
104   }
105 };
106 
107 // Left/right rotation.
108 struct RotOp : public SetIntBinOp {
109   const bool Reverse;
110 
RotOp__anone0c51e680111::RotOp111   RotOp(bool Rev) : Reverse(Rev) {}
112 
apply2__anone0c51e680111::RotOp113   void apply2(SetTheory &ST, DagInit *Expr,
114              RecSet &Set, int64_t N,
115              RecSet &Elts) {
116     if (Reverse)
117       N = -N;
118     // N > 0 -> rotate left, N < 0 -> rotate right.
119     if (Set.empty())
120       return;
121     if (N < 0)
122       N = Set.size() - (-N % Set.size());
123     else
124       N %= Set.size();
125     Elts.insert(Set.begin() + N, Set.end());
126     Elts.insert(Set.begin(), Set.begin() + N);
127   }
128 };
129 
130 // (decimate S, N) Pick every N'th element of S.
131 struct DecimateOp : public SetIntBinOp {
apply2__anone0c51e680111::DecimateOp132   void apply2(SetTheory &ST, DagInit *Expr,
133              RecSet &Set, int64_t N,
134              RecSet &Elts) {
135     if (N <= 0)
136       throw "Positive stride required: " + Expr->getAsString();
137     for (unsigned I = 0; I < Set.size(); I += N)
138       Elts.insert(Set[I]);
139   }
140 };
141 
142 // (interleave S1, S2, ...) Interleave elements of the arguments.
143 struct InterleaveOp : public SetTheory::Operator {
apply__anone0c51e680111::InterleaveOp144   void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts) {
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]);
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 
160 // (sequence "Format", From, To) Generate a sequence of records by name.
161 struct SequenceOp : public SetTheory::Operator {
apply__anone0c51e680111::SequenceOp162   void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts) {
163     if (Expr->arg_size() != 3)
164       throw "Bad args to (sequence \"Format\", From, To): " +
165         Expr->getAsString();
166     std::string Format;
167     if (StringInit *SI = dynamic_cast<StringInit*>(Expr->arg_begin()[0]))
168       Format = SI->getValue();
169     else
170       throw "Format must be a string: " + Expr->getAsString();
171 
172     int64_t From, To;
173     if (IntInit *II = dynamic_cast<IntInit*>(Expr->arg_begin()[1]))
174       From = II->getValue();
175     else
176       throw "From must be an integer: " + Expr->getAsString();
177     if (From < 0 || From >= (1 << 30))
178       throw "From out of range";
179 
180     if (IntInit *II = dynamic_cast<IntInit*>(Expr->arg_begin()[2]))
181       To = II->getValue();
182     else
183       throw "From must be an integer: " + Expr->getAsString();
184     if (To < 0 || To >= (1 << 30))
185       throw "To out of range";
186 
187     RecordKeeper &Records =
188       dynamic_cast<DefInit&>(*Expr->getOperator()).getDef()->getRecords();
189 
190     int Step = From <= To ? 1 : -1;
191     for (To += Step; From != To; From += Step) {
192       std::string Name;
193       raw_string_ostream OS(Name);
194       OS << format(Format.c_str(), unsigned(From));
195       Record *Rec = Records.getDef(OS.str());
196       if (!Rec)
197         throw "No def named '" + Name + "': " + Expr->getAsString();
198       // Try to reevaluate Rec in case it is a set.
199       if (const RecVec *Result = ST.expand(Rec))
200         Elts.insert(Result->begin(), Result->end());
201       else
202         Elts.insert(Rec);
203     }
204   }
205 };
206 
207 // Expand a Def into a set by evaluating one of its fields.
208 struct FieldExpander : public SetTheory::Expander {
209   StringRef FieldName;
210 
FieldExpander__anone0c51e680111::FieldExpander211   FieldExpander(StringRef fn) : FieldName(fn) {}
212 
expand__anone0c51e680111::FieldExpander213   void expand(SetTheory &ST, Record *Def, RecSet &Elts) {
214     ST.evaluate(Def->getValueInit(FieldName), Elts);
215   }
216 };
217 } // end anonymous namespace
218 
anchor()219 void SetTheory::Operator::anchor() { }
220 
anchor()221 void SetTheory::Expander::anchor() { }
222 
SetTheory()223 SetTheory::SetTheory() {
224   addOperator("add", new AddOp);
225   addOperator("sub", new SubOp);
226   addOperator("and", new AndOp);
227   addOperator("shl", new ShlOp);
228   addOperator("trunc", new TruncOp);
229   addOperator("rotl", new RotOp(false));
230   addOperator("rotr", new RotOp(true));
231   addOperator("decimate", new DecimateOp);
232   addOperator("interleave", new InterleaveOp);
233   addOperator("sequence", new SequenceOp);
234 }
235 
addOperator(StringRef Name,Operator * Op)236 void SetTheory::addOperator(StringRef Name, Operator *Op) {
237   Operators[Name] = Op;
238 }
239 
addExpander(StringRef ClassName,Expander * E)240 void SetTheory::addExpander(StringRef ClassName, Expander *E) {
241   Expanders[ClassName] = E;
242 }
243 
addFieldExpander(StringRef ClassName,StringRef FieldName)244 void SetTheory::addFieldExpander(StringRef ClassName, StringRef FieldName) {
245   addExpander(ClassName, new FieldExpander(FieldName));
246 }
247 
evaluate(Init * Expr,RecSet & Elts)248 void SetTheory::evaluate(Init *Expr, RecSet &Elts) {
249   // A def in a list can be a just an element, or it may expand.
250   if (DefInit *Def = dynamic_cast<DefInit*>(Expr)) {
251     if (const RecVec *Result = expand(Def->getDef()))
252       return Elts.insert(Result->begin(), Result->end());
253     Elts.insert(Def->getDef());
254     return;
255   }
256 
257   // Lists simply expand.
258   if (ListInit *LI = dynamic_cast<ListInit*>(Expr))
259     return evaluate(LI->begin(), LI->end(), Elts);
260 
261   // Anything else must be a DAG.
262   DagInit *DagExpr = dynamic_cast<DagInit*>(Expr);
263   if (!DagExpr)
264     throw "Invalid set element: " + Expr->getAsString();
265   DefInit *OpInit = dynamic_cast<DefInit*>(DagExpr->getOperator());
266   if (!OpInit)
267     throw "Bad set expression: " + Expr->getAsString();
268   Operator *Op = Operators.lookup(OpInit->getDef()->getName());
269   if (!Op)
270     throw "Unknown set operator: " + Expr->getAsString();
271   Op->apply(*this, DagExpr, Elts);
272 }
273 
expand(Record * Set)274 const RecVec *SetTheory::expand(Record *Set) {
275   // Check existing entries for Set and return early.
276   ExpandMap::iterator I = Expansions.find(Set);
277   if (I != Expansions.end())
278     return &I->second;
279 
280   // This is the first time we see Set. Find a suitable expander.
281   try {
282     const std::vector<Record*> &SC = Set->getSuperClasses();
283     for (unsigned i = 0, e = SC.size(); i != e; ++i)
284       if (Expander *Exp = Expanders.lookup(SC[i]->getName())) {
285         // This breaks recursive definitions.
286         RecVec &EltVec = Expansions[Set];
287         RecSet Elts;
288         Exp->expand(*this, Set, Elts);
289         EltVec.assign(Elts.begin(), Elts.end());
290         return &EltVec;
291       }
292   } catch (const std::string &Error) {
293     throw TGError(Set->getLoc(), Error);
294   }
295 
296   // Set is not expandable.
297   return 0;
298 }
299 
300