Do not remove an active template argument even if the superclass had one of the
[oota-llvm.git] / utils / TableGen / FileParser.y
1 //===-- FileParser.y - Parser for TableGen files ----------------*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the bison parser for Table Generator files...
11 //
12 //===----------------------------------------------------------------------===//
13
14 %{
15 #include "Record.h"
16 #include "Support/StringExtras.h"
17 #include <algorithm>
18 #include <cstdio>
19 #define YYERROR_VERBOSE 1
20
21 int yyerror(const char *ErrorMsg);
22 int yylex();
23
24 namespace llvm {
25
26 extern int Filelineno;
27 static Record *CurRec = 0;
28
29 typedef std::pair<Record*, std::vector<Init*>*> SubClassRefTy;
30
31 struct LetRecord {
32   std::string Name;
33   std::vector<unsigned> Bits;
34   Init *Value;
35   bool HasBits;
36   LetRecord(const std::string &N, std::vector<unsigned> *B, Init *V)
37     : Name(N), Value(V), HasBits(B != 0) {
38     if (HasBits) Bits = *B;
39   }
40 };
41
42 static std::vector<std::vector<LetRecord> > LetStack;
43
44
45 extern std::ostream &err();
46
47 static void addValue(const RecordVal &RV) {
48   if (RecordVal *ERV = CurRec->getValue(RV.getName())) {
49     // The value already exists in the class, treat this as a set...
50     if (ERV->setValue(RV.getValue())) {
51       err() << "New definition of '" << RV.getName() << "' of type '"
52             << *RV.getType() << "' is incompatible with previous "
53             << "definition of type '" << *ERV->getType() << "'!\n";
54       exit(1);
55     }
56   } else {
57     CurRec->addValue(RV);
58   }
59 }
60
61 static void addSuperClass(Record *SC) {
62   if (CurRec->isSubClassOf(SC)) {
63     err() << "Already subclass of '" << SC->getName() << "'!\n";
64     exit(1);
65   }
66   CurRec->addSuperClass(SC);
67 }
68
69 static void setValue(const std::string &ValName, 
70                      std::vector<unsigned> *BitList, Init *V) {
71   if (!V) return;
72
73   RecordVal *RV = CurRec->getValue(ValName);
74   if (RV == 0) {
75     err() << "Value '" << ValName << "' unknown!\n";
76     exit(1);
77   }
78
79   // Do not allow assignments like 'X = X'.  This will just cause infinite loops
80   // in the resolution machinery.
81   if (!BitList)
82     if (VarInit *VI = dynamic_cast<VarInit*>(V))
83       if (VI->getName() == ValName)
84         return;
85   
86   // If we are assigning to a subset of the bits in the value... then we must be
87   // assigning to a field of BitsRecTy, which must have a BitsInit
88   // initializer...
89   //
90   if (BitList) {
91     BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
92     if (CurVal == 0) {
93       err() << "Value '" << ValName << "' is not a bits type!\n";
94       exit(1);
95     }
96
97     // Convert the incoming value to a bits type of the appropriate size...
98     Init *BI = V->convertInitializerTo(new BitsRecTy(BitList->size()));
99     if (BI == 0) {
100       V->convertInitializerTo(new BitsRecTy(BitList->size()));
101       err() << "Initializer '" << *V << "' not compatible with bit range!\n";
102       exit(1);
103     }
104
105     // We should have a BitsInit type now...
106     assert(dynamic_cast<BitsInit*>(BI) != 0 || &(std::cerr << *BI) == 0);
107     BitsInit *BInit = (BitsInit*)BI;
108
109     BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
110
111     // Loop over bits, assigning values as appropriate...
112     for (unsigned i = 0, e = BitList->size(); i != e; ++i) {
113       unsigned Bit = (*BitList)[i];
114       if (NewVal->getBit(Bit)) {
115         err() << "Cannot set bit #" << Bit << " of value '" << ValName
116               << "' more than once!\n";
117         exit(1);
118       }
119       NewVal->setBit(Bit, BInit->getBit(i));
120     }
121
122     for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
123       if (NewVal->getBit(i) == 0)
124         NewVal->setBit(i, CurVal->getBit(i));
125
126     V = NewVal;
127   }
128
129   if (RV->setValue(V)) {
130     err() << "Value '" << ValName << "' of type '" << *RV->getType()
131           << "' is incompatible with initializer '" << *V << "'!\n";
132     exit(1);
133   }
134 }
135
136 static void addSubClass(Record *SC, const std::vector<Init*> &TemplateArgs) {
137   // Add all of the values in the subclass into the current class...
138   const std::vector<RecordVal> &Vals = SC->getValues();
139   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
140     addValue(Vals[i]);
141
142   const std::vector<std::string> &TArgs = SC->getTemplateArgs();
143
144   // Ensure that an appropriate number of template arguments are specified...
145   if (TArgs.size() < TemplateArgs.size()) {
146     err() << "ERROR: More template args specified than expected!\n";
147     exit(1);
148   } else {    // This class expects template arguments...
149     // Loop over all of the template arguments, setting them to the specified
150     // value or leaving them as the default as necessary.
151     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
152       if (i < TemplateArgs.size()) {  // A value is specified for this temp-arg?
153         // Set it now.
154         setValue(TArgs[i], 0, TemplateArgs[i]);
155       } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
156         err() << "ERROR: Value not specified for template argument #"
157               << i << " (" << TArgs[i] << ") of subclass '" << SC->getName()
158               << "'!\n";
159         exit(1);
160       }
161     }
162   }
163
164   // Since everything went well, we can now set the "superclass" list for the
165   // current record.
166   const std::vector<Record*> &SCs  = SC->getSuperClasses();
167   for (unsigned i = 0, e = SCs.size(); i != e; ++i)
168     addSuperClass(SCs[i]);
169   addSuperClass(SC);
170 }
171
172 } // End llvm namespace
173
174 using namespace llvm;
175
176 %}
177
178 %union {
179   std::string*                StrVal;
180   int                         IntVal;
181   llvm::RecTy*                Ty;
182   llvm::Init*                 Initializer;
183   std::vector<llvm::Init*>*   FieldList;
184   std::vector<unsigned>*      BitList;
185   llvm::Record*               Rec;
186   SubClassRefTy*              SubClassRef;
187   std::vector<SubClassRefTy>* SubClassList;
188   std::vector<std::pair<llvm::Init*, std::string> >* DagValueList;
189 };
190
191 %token INT BIT STRING BITS LIST CODE DAG CLASS DEF FIELD LET IN
192 %token <IntVal>      INTVAL
193 %token <StrVal>      ID VARNAME STRVAL CODEFRAGMENT
194
195 %type <Ty>           Type
196 %type <Rec>          ClassInst DefInst Object ObjectBody ClassID
197
198 %type <SubClassRef>  SubClassRef
199 %type <SubClassList> ClassList ClassListNE
200 %type <IntVal>       OptPrefix
201 %type <Initializer>  Value OptValue
202 %type <DagValueList> DagArgList DagArgListNE
203 %type <FieldList>    ValueList ValueListNE
204 %type <BitList>      BitList OptBitList RBitList
205 %type <StrVal>       Declaration OptID OptVarName
206
207 %start File
208
209 %%
210
211 ClassID : ID {
212     $$ = Records.getClass(*$1);
213     if ($$ == 0) {
214       err() << "Couldn't find class '" << *$1 << "'!\n";
215       exit(1);
216     }
217     delete $1;
218   };
219
220
221 // TableGen types...
222 Type : STRING {                       // string type
223     $$ = new StringRecTy();
224   } | BIT {                           // bit type
225     $$ = new BitRecTy();
226   } | BITS '<' INTVAL '>' {           // bits<x> type
227     $$ = new BitsRecTy($3);
228   } | INT {                           // int type
229     $$ = new IntRecTy();
230   } | LIST '<' Type '>'    {          // list<x> type
231     $$ = new ListRecTy($3);
232   } | CODE {                          // code type
233     $$ = new CodeRecTy();
234   } | DAG {                           // dag type
235     $$ = new DagRecTy();
236   } | ClassID {                       // Record Type
237     $$ = new RecordRecTy($1);
238   };
239
240 OptPrefix : /*empty*/ { $$ = 0; } | FIELD { $$ = 1; };
241
242 OptValue : /*empty*/ { $$ = 0; } | '=' Value { $$ = $2; };
243
244 Value : INTVAL {
245     $$ = new IntInit($1);
246   } | STRVAL {
247     $$ = new StringInit(*$1);
248     delete $1;
249   } | CODEFRAGMENT {
250     $$ = new CodeInit(*$1);
251     delete $1;
252   } | '?' {
253     $$ = new UnsetInit();
254   } | '{' ValueList '}' {
255     BitsInit *Init = new BitsInit($2->size());
256     for (unsigned i = 0, e = $2->size(); i != e; ++i) {
257       struct Init *Bit = (*$2)[i]->convertInitializerTo(new BitRecTy());
258       if (Bit == 0) {
259         err() << "Element #" << i << " (" << *(*$2)[i]
260               << ") is not convertable to a bit!\n";
261         exit(1);
262       }
263       Init->setBit($2->size()-i-1, Bit);
264     }
265     $$ = Init;
266     delete $2;
267   } | ID {
268     if (const RecordVal *RV = (CurRec ? CurRec->getValue(*$1) : 0)) {
269       $$ = new VarInit(*$1, RV->getType());
270     } else if (Record *D = Records.getDef(*$1)) {
271       $$ = new DefInit(D);
272     } else {
273       err() << "Variable not defined: '" << *$1 << "'!\n";
274       exit(1);
275     }
276     
277     delete $1;
278   } | Value '{' BitList '}' {
279     $$ = $1->convertInitializerBitRange(*$3);
280     if ($$ == 0) {
281       err() << "Invalid bit range for value '" << *$1 << "'!\n";
282       exit(1);
283     }
284     delete $3;
285   } | '[' ValueList ']' {
286     $$ = new ListInit(*$2);
287     delete $2;
288   } | Value '.' ID {
289     if (!$1->getFieldType(*$3)) {
290       err() << "Cannot access field '" << *$3 << "' of value '" << *$1 << "!\n";
291       exit(1);
292     }
293     $$ = new FieldInit($1, *$3);
294     delete $3;
295   } | '(' ID DagArgList ')' {
296     Record *D = Records.getDef(*$2);
297     if (D == 0) {
298       err() << "Invalid def '" << *$2 << "'!\n";
299       exit(1);
300     }
301     $$ = new DagInit(D, *$3);
302     delete $2; delete $3;
303   };
304
305 OptVarName : /* empty */ {
306     $$ = new std::string();
307   }
308   | ':' VARNAME {
309     $$ = $2;
310   };
311
312 DagArgListNE : Value OptVarName {
313     $$ = new std::vector<std::pair<Init*, std::string> >();
314     $$->push_back(std::make_pair($1, *$2));
315     delete $2;
316   }
317   | DagArgListNE ',' Value OptVarName {
318     $1->push_back(std::make_pair($3, *$4));
319     delete $4;
320     $$ = $1;
321   };
322
323 DagArgList : /*empty*/ {
324     $$ = new std::vector<std::pair<Init*, std::string> >();
325   }
326   | DagArgListNE { $$ = $1; };
327
328
329 RBitList : INTVAL {
330     $$ = new std::vector<unsigned>();
331     $$->push_back($1);
332   } | INTVAL '-' INTVAL {
333     if ($1 < $3 || $1 < 0 || $3 < 0) {
334       err() << "Invalid bit range: " << $1 << "-" << $3 << "!\n";
335       exit(1);
336     }
337     $$ = new std::vector<unsigned>();
338     for (int i = $1; i >= $3; --i)
339       $$->push_back(i);
340   } | INTVAL INTVAL {
341     $2 = -$2;
342     if ($1 < $2 || $1 < 0 || $2 < 0) {
343       err() << "Invalid bit range: " << $1 << "-" << $2 << "!\n";
344       exit(1);
345     }
346     $$ = new std::vector<unsigned>();
347     for (int i = $1; i >= $2; --i)
348       $$->push_back(i);
349   } | RBitList ',' INTVAL {
350     ($$=$1)->push_back($3);
351   } | RBitList ',' INTVAL '-' INTVAL {
352     if ($3 < $5 || $3 < 0 || $5 < 0) {
353       err() << "Invalid bit range: " << $3 << "-" << $5 << "!\n";
354       exit(1);
355     }
356     $$ = $1;
357     for (int i = $3; i >= $5; --i)
358       $$->push_back(i);
359   } | RBitList ',' INTVAL INTVAL {
360     $4 = -$4;
361     if ($3 < $4 || $3 < 0 || $4 < 0) {
362       err() << "Invalid bit range: " << $3 << "-" << $4 << "!\n";
363       exit(1);
364     }
365     $$ = $1;
366     for (int i = $3; i >= $4; --i)
367       $$->push_back(i);
368   };
369
370 BitList : RBitList { $$ = $1; std::reverse($1->begin(), $1->end()); };
371
372 OptBitList : /*empty*/ { $$ = 0; } | '{' BitList '}' { $$ = $2; };
373
374
375
376 ValueList : /*empty*/ {
377     $$ = new std::vector<Init*>();
378   } | ValueListNE {
379     $$ = $1;
380   };
381
382 ValueListNE : Value {
383     $$ = new std::vector<Init*>();
384     $$->push_back($1);
385   } | ValueListNE ',' Value {
386     ($$ = $1)->push_back($3);
387   };
388
389 Declaration : OptPrefix Type ID OptValue {
390   addValue(RecordVal(*$3, $2, $1));
391   setValue(*$3, 0, $4);
392   $$ = $3;
393 };
394
395 BodyItem : Declaration ';' {
396   delete $1;
397 } | LET ID OptBitList '=' Value ';' {
398   setValue(*$2, $3, $5);
399   delete $2;
400   delete $3;
401 };
402
403 BodyList : /*empty*/ | BodyList BodyItem;
404 Body : ';' | '{' BodyList '}';
405
406 SubClassRef : ClassID {
407     $$ = new SubClassRefTy($1, new std::vector<Init*>());
408   } | ClassID '<' ValueListNE '>' {
409     $$ = new SubClassRefTy($1, $3);
410   };
411
412 ClassListNE : SubClassRef {
413     $$ = new std::vector<SubClassRefTy>();
414     $$->push_back(*$1);
415     delete $1;
416   }
417   | ClassListNE ',' SubClassRef {
418     ($$=$1)->push_back(*$3);
419     delete $3;
420   };
421
422 ClassList : /*empty */ {
423     $$ = new std::vector<SubClassRefTy>();
424   }
425   | ':' ClassListNE {
426     $$ = $2;
427   };
428
429 DeclListNE : Declaration {
430   CurRec->addTemplateArg(*$1);
431   delete $1;
432 } | DeclListNE ',' Declaration {
433   CurRec->addTemplateArg(*$3);
434   delete $3;
435 };
436
437 TemplateArgList : '<' DeclListNE '>' {};
438 OptTemplateArgList : /*empty*/ | TemplateArgList;
439
440 OptID : ID { $$ = $1; } | /*empty*/ { $$ = new std::string(); };
441
442 ObjectBody : OptID {
443            static unsigned AnonCounter = 0;
444            if ($1->empty())
445              *$1 = "anonymous."+utostr(AnonCounter++);
446            CurRec = new Record(*$1);
447            delete $1;
448          } OptTemplateArgList ClassList {
449            for (unsigned i = 0, e = $4->size(); i != e; ++i) {
450              addSubClass((*$4)[i].first, *(*$4)[i].second);
451              // Delete the template arg values for the class
452              delete (*$4)[i].second;
453            }
454
455            // Process any variables on the set stack...
456            for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
457              for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
458                setValue(LetStack[i][j].Name,
459                         LetStack[i][j].HasBits ? &LetStack[i][j].Bits : 0,
460                         LetStack[i][j].Value);
461          } Body {
462   CurRec->resolveReferences();
463
464   // Now that all of the references have been resolved, we can delete template
465   // arguments for superclasses, so they don't pollute our record, and so that
466   // their names won't conflict with later uses of the name...
467   for (unsigned i = 0, e = $4->size(); i != e; ++i) {
468     Record *SuperClass = (*$4)[i].first;
469     for (unsigned i = 0, e = SuperClass->getTemplateArgs().size(); i != e; ++i)
470       if (!CurRec->isTemplateArg(SuperClass->getTemplateArgs()[i]))
471         CurRec->removeValue(SuperClass->getTemplateArgs()[i]);
472   }
473   delete $4;   // Delete the class list...
474
475   $$ = CurRec;
476   CurRec = 0;
477 };
478
479 ClassInst : CLASS ObjectBody {
480   if (Records.getClass($2->getName())) {
481     err() << "Class '" << $2->getName() << "' already defined!\n";
482     exit(1);
483   }
484   Records.addClass($$ = $2);
485 };
486
487 DefInst : DEF ObjectBody {
488   if (!$2->getTemplateArgs().empty()) {
489     err() << "Def '" << $2->getName()
490           << "' is not permitted to have template arguments!\n";
491     exit(1);
492   }
493   // If ObjectBody has template arguments, it's an error.
494   if (Records.getDef($2->getName())) {
495     err() << "Def '" << $2->getName() << "' already defined!\n";
496     exit(1);
497   }
498   Records.addDef($$ = $2);
499 };
500
501
502 Object : ClassInst | DefInst;
503
504 LETItem : ID OptBitList '=' Value {
505   LetStack.back().push_back(LetRecord(*$1, $2, $4));
506   delete $1; delete $2;
507 };
508
509 LETList : LETItem | LETList ',' LETItem;
510
511 // LETCommand - A 'LET' statement start...
512 LETCommand : LET { LetStack.push_back(std::vector<LetRecord>()); } LETList IN;
513
514 // Support Set commands wrapping objects... both with and without braces.
515 Object : LETCommand '{' ObjectList '}' {
516     LetStack.pop_back();
517   }
518   | LETCommand Object {
519     LetStack.pop_back();
520   };
521
522 ObjectList : Object {} | ObjectList Object {};
523
524 File : ObjectList {};
525
526 %%
527
528 int yyerror(const char *ErrorMsg) {
529   err() << "Error parsing: " << ErrorMsg << "\n";
530   exit(1);
531 }