Implement !if, analogous to $(if) in GNU make.
[oota-llvm.git] / utils / TableGen / TGParser.cpp
1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
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 // Implement the Parser for TableGen.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include <algorithm>
15
16 #include "TGParser.h"
17 #include "Record.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Support/Streams.h"
20 using namespace llvm;
21
22 //===----------------------------------------------------------------------===//
23 // Support Code for the Semantic Actions.
24 //===----------------------------------------------------------------------===//
25
26 namespace llvm {
27 struct SubClassReference {
28   TGLoc RefLoc;
29   Record *Rec;
30   std::vector<Init*> TemplateArgs;
31   SubClassReference() : Rec(0) {}
32
33   bool isInvalid() const { return Rec == 0; }
34 };
35
36 struct SubMultiClassReference {
37   TGLoc RefLoc;
38   MultiClass *MC;
39   std::vector<Init*> TemplateArgs;
40   SubMultiClassReference() : MC(0) {}
41
42   bool isInvalid() const { return MC == 0; }
43   void dump() const;
44 };
45
46 void SubMultiClassReference::dump() const {
47   cerr << "Multiclass:\n";
48  
49   MC->dump();
50  
51   cerr << "Template args:\n";
52   for (std::vector<Init *>::const_iterator i = TemplateArgs.begin(),
53          iend = TemplateArgs.end();
54        i != iend;
55        ++i) {
56     (*i)->dump();
57   }
58 }
59
60 } // end namespace llvm
61
62 bool TGParser::AddValue(Record *CurRec, TGLoc Loc, const RecordVal &RV) {
63   if (CurRec == 0)
64     CurRec = &CurMultiClass->Rec;
65   
66   if (RecordVal *ERV = CurRec->getValue(RV.getName())) {
67     // The value already exists in the class, treat this as a set.
68     if (ERV->setValue(RV.getValue()))
69       return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
70                    RV.getType()->getAsString() + "' is incompatible with " +
71                    "previous definition of type '" + 
72                    ERV->getType()->getAsString() + "'");
73   } else {
74     CurRec->addValue(RV);
75   }
76   return false;
77 }
78
79 /// SetValue -
80 /// Return true on error, false on success.
81 bool TGParser::SetValue(Record *CurRec, TGLoc Loc, const std::string &ValName, 
82                         const std::vector<unsigned> &BitList, Init *V) {
83   if (!V) return false;
84
85   if (CurRec == 0) CurRec = &CurMultiClass->Rec;
86
87   RecordVal *RV = CurRec->getValue(ValName);
88   if (RV == 0)
89     return Error(Loc, "Value '" + ValName + "' unknown!");
90
91   // Do not allow assignments like 'X = X'.  This will just cause infinite loops
92   // in the resolution machinery.
93   if (BitList.empty())
94     if (VarInit *VI = dynamic_cast<VarInit*>(V))
95       if (VI->getName() == ValName)
96         return false;
97   
98   // If we are assigning to a subset of the bits in the value... then we must be
99   // assigning to a field of BitsRecTy, which must have a BitsInit
100   // initializer.
101   //
102   if (!BitList.empty()) {
103     BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
104     if (CurVal == 0)
105       return Error(Loc, "Value '" + ValName + "' is not a bits type");
106
107     // Convert the incoming value to a bits type of the appropriate size...
108     Init *BI = V->convertInitializerTo(new BitsRecTy(BitList.size()));
109     if (BI == 0) {
110       V->convertInitializerTo(new BitsRecTy(BitList.size()));
111       return Error(Loc, "Initializer is not compatible with bit range");
112     }
113                    
114     // We should have a BitsInit type now.
115     BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
116     assert(BInit != 0);
117
118     BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
119
120     // Loop over bits, assigning values as appropriate.
121     for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
122       unsigned Bit = BitList[i];
123       if (NewVal->getBit(Bit))
124         return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
125                      ValName + "' more than once");
126       NewVal->setBit(Bit, BInit->getBit(i));
127     }
128
129     for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
130       if (NewVal->getBit(i) == 0)
131         NewVal->setBit(i, CurVal->getBit(i));
132
133     V = NewVal;
134   }
135
136   if (RV->setValue(V))
137    return Error(Loc, "Value '" + ValName + "' of type '" + 
138                 RV->getType()->getAsString() + 
139                 "' is incompatible with initializer '" + V->getAsString() +"'");
140   return false;
141 }
142
143 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
144 /// args as SubClass's template arguments.
145 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
146   Record *SC = SubClass.Rec;
147   // Add all of the values in the subclass into the current class.
148   const std::vector<RecordVal> &Vals = SC->getValues();
149   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
150     if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
151       return true;
152
153   const std::vector<std::string> &TArgs = SC->getTemplateArgs();
154
155   // Ensure that an appropriate number of template arguments are specified.
156   if (TArgs.size() < SubClass.TemplateArgs.size())
157     return Error(SubClass.RefLoc, "More template args specified than expected");
158   
159   // Loop over all of the template arguments, setting them to the specified
160   // value or leaving them as the default if necessary.
161   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
162     if (i < SubClass.TemplateArgs.size()) {
163       // If a value is specified for this template arg, set it now.
164       if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(), 
165                    SubClass.TemplateArgs[i]))
166         return true;
167       
168       // Resolve it next.
169       CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
170       
171       // Now remove it.
172       CurRec->removeValue(TArgs[i]);
173
174     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
175       return Error(SubClass.RefLoc,"Value not specified for template argument #"
176                    + utostr(i) + " (" + TArgs[i] + ") of subclass '" + 
177                    SC->getName() + "'!");
178     }
179   }
180
181   // Since everything went well, we can now set the "superclass" list for the
182   // current record.
183   const std::vector<Record*> &SCs = SC->getSuperClasses();
184   for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
185     if (CurRec->isSubClassOf(SCs[i]))
186       return Error(SubClass.RefLoc,
187                    "Already subclass of '" + SCs[i]->getName() + "'!\n");
188     CurRec->addSuperClass(SCs[i]);
189   }
190   
191   if (CurRec->isSubClassOf(SC))
192     return Error(SubClass.RefLoc,
193                  "Already subclass of '" + SC->getName() + "'!\n");
194   CurRec->addSuperClass(SC);
195   return false;
196 }
197
198 /// AddSubMultiClass - Add SubMultiClass as a subclass to
199 /// CurMC, resolving its template args as SubMultiClass's
200 /// template arguments.
201 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
202                                 SubMultiClassReference &SubMultiClass) {
203   MultiClass *SMC = SubMultiClass.MC;
204   Record *CurRec = &CurMC->Rec;
205
206   const std::vector<RecordVal> &MCVals = CurRec->getValues();
207
208   // Add all of the values in the subclass into the current class.
209   const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
210   for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
211     if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
212       return true;
213
214   int newDefStart = CurMC->DefPrototypes.size();
215
216   // Add all of the defs in the subclass into the current multiclass.
217   for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
218          iend = SMC->DefPrototypes.end();
219        i != iend;
220        ++i) {
221     // Clone the def and add it to the current multiclass
222     Record *NewDef = new Record(**i);
223
224     // Add all of the values in the superclass into the current def.
225     for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
226       if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
227         return true;
228
229     CurMC->DefPrototypes.push_back(NewDef);
230   }
231
232   const std::vector<std::string> &SMCTArgs = SMC->Rec.getTemplateArgs();
233
234   // Ensure that an appropriate number of template arguments are
235   // specified.
236   if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
237     return Error(SubMultiClass.RefLoc,
238                  "More template args specified than expected");
239
240   // Loop over all of the template arguments, setting them to the specified
241   // value or leaving them as the default if necessary.
242   for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
243     if (i < SubMultiClass.TemplateArgs.size()) {
244       // If a value is specified for this template arg, set it in the
245       // superclass now.
246       if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i],
247                    std::vector<unsigned>(),
248                    SubMultiClass.TemplateArgs[i]))
249         return true;
250
251       // Resolve it next.
252       CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
253
254       // Now remove it.
255       CurRec->removeValue(SMCTArgs[i]);
256
257       // If a value is specified for this template arg, set it in the
258       // new defs now.
259       for (MultiClass::RecordVector::iterator j =
260              CurMC->DefPrototypes.begin() + newDefStart,
261              jend = CurMC->DefPrototypes.end();
262            j != jend;
263            ++j) {
264         Record *Def = *j;
265
266         if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i],
267                      std::vector<unsigned>(),
268                      SubMultiClass.TemplateArgs[i]))
269           return true;
270
271         // Resolve it next.
272         Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
273
274         // Now remove it
275         Def->removeValue(SMCTArgs[i]);
276       }
277     } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
278       return Error(SubMultiClass.RefLoc,
279                    "Value not specified for template argument #"
280                    + utostr(i) + " (" + SMCTArgs[i] + ") of subclass '" +
281                    SMC->Rec.getName() + "'!");
282     }
283   }
284
285   return false;
286 }
287
288 //===----------------------------------------------------------------------===//
289 // Parser Code
290 //===----------------------------------------------------------------------===//
291
292 /// isObjectStart - Return true if this is a valid first token for an Object.
293 static bool isObjectStart(tgtok::TokKind K) {
294   return K == tgtok::Class || K == tgtok::Def ||
295          K == tgtok::Defm || K == tgtok::Let || K == tgtok::MultiClass; 
296 }
297
298 /// ParseObjectName - If an object name is specified, return it.  Otherwise,
299 /// return an anonymous name.
300 ///   ObjectName ::= ID
301 ///   ObjectName ::= /*empty*/
302 ///
303 std::string TGParser::ParseObjectName() {
304   if (Lex.getCode() == tgtok::Id) {
305     std::string Ret = Lex.getCurStrVal();
306     Lex.Lex();
307     return Ret;
308   }
309   
310   static unsigned AnonCounter = 0;
311   return "anonymous."+utostr(AnonCounter++);
312 }
313
314
315 /// ParseClassID - Parse and resolve a reference to a class name.  This returns
316 /// null on error.
317 ///
318 ///    ClassID ::= ID
319 ///
320 Record *TGParser::ParseClassID() {
321   if (Lex.getCode() != tgtok::Id) {
322     TokError("expected name for ClassID");
323     return 0;
324   }
325   
326   Record *Result = Records.getClass(Lex.getCurStrVal());
327   if (Result == 0)
328     TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
329   
330   Lex.Lex();
331   return Result;
332 }
333
334 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
335 /// This returns null on error.
336 ///
337 ///    MultiClassID ::= ID
338 ///
339 MultiClass *TGParser::ParseMultiClassID() {
340   if (Lex.getCode() != tgtok::Id) {
341     TokError("expected name for ClassID");
342     return 0;
343   }
344
345   MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
346   if (Result == 0)
347     TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
348
349   Lex.Lex();
350   return Result;
351 }
352
353 Record *TGParser::ParseDefmID() {
354   if (Lex.getCode() != tgtok::Id) {
355     TokError("expected multiclass name");
356     return 0;
357   }
358   
359   MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
360   if (MC == 0) {
361     TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
362     return 0;
363   }
364   
365   Lex.Lex();
366   return &MC->Rec;
367 }  
368
369
370
371 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
372 /// subclass.  This returns a SubClassRefTy with a null Record* on error.
373 ///
374 ///  SubClassRef ::= ClassID
375 ///  SubClassRef ::= ClassID '<' ValueList '>'
376 ///
377 SubClassReference TGParser::
378 ParseSubClassReference(Record *CurRec, bool isDefm) {
379   SubClassReference Result;
380   Result.RefLoc = Lex.getLoc();
381   
382   if (isDefm)
383     Result.Rec = ParseDefmID();
384   else
385     Result.Rec = ParseClassID();
386   if (Result.Rec == 0) return Result;
387   
388   // If there is no template arg list, we're done.
389   if (Lex.getCode() != tgtok::less)
390     return Result;
391   Lex.Lex();  // Eat the '<'
392   
393   if (Lex.getCode() == tgtok::greater) {
394     TokError("subclass reference requires a non-empty list of template values");
395     Result.Rec = 0;
396     return Result;
397   }
398   
399   Result.TemplateArgs = ParseValueList(CurRec);
400   if (Result.TemplateArgs.empty()) {
401     Result.Rec = 0;   // Error parsing value list.
402     return Result;
403   }
404     
405   if (Lex.getCode() != tgtok::greater) {
406     TokError("expected '>' in template value list");
407     Result.Rec = 0;
408     return Result;
409   }
410   Lex.Lex();
411   
412   return Result;
413 }
414
415 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
416 /// templated submulticlass.  This returns a SubMultiClassRefTy with a null
417 /// Record* on error.
418 ///
419 ///  SubMultiClassRef ::= MultiClassID
420 ///  SubMultiClassRef ::= MultiClassID '<' ValueList '>'
421 ///
422 SubMultiClassReference TGParser::
423 ParseSubMultiClassReference(MultiClass *CurMC) {
424   SubMultiClassReference Result;
425   Result.RefLoc = Lex.getLoc();
426
427   Result.MC = ParseMultiClassID();
428   if (Result.MC == 0) return Result;
429
430   // If there is no template arg list, we're done.
431   if (Lex.getCode() != tgtok::less)
432     return Result;
433   Lex.Lex();  // Eat the '<'
434
435   if (Lex.getCode() == tgtok::greater) {
436     TokError("subclass reference requires a non-empty list of template values");
437     Result.MC = 0;
438     return Result;
439   }
440
441   Result.TemplateArgs = ParseValueList(&CurMC->Rec);
442   if (Result.TemplateArgs.empty()) {
443     Result.MC = 0;   // Error parsing value list.
444     return Result;
445   }
446
447   if (Lex.getCode() != tgtok::greater) {
448     TokError("expected '>' in template value list");
449     Result.MC = 0;
450     return Result;
451   }
452   Lex.Lex();
453
454   return Result;
455 }
456
457 /// ParseRangePiece - Parse a bit/value range.
458 ///   RangePiece ::= INTVAL
459 ///   RangePiece ::= INTVAL '-' INTVAL
460 ///   RangePiece ::= INTVAL INTVAL
461 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
462   if (Lex.getCode() != tgtok::IntVal) {
463     TokError("expected integer or bitrange");
464     return true;
465   }
466   int64_t Start = Lex.getCurIntVal();
467   int64_t End;
468   
469   if (Start < 0)
470     return TokError("invalid range, cannot be negative");
471   
472   switch (Lex.Lex()) {  // eat first character.
473   default: 
474     Ranges.push_back(Start);
475     return false;
476   case tgtok::minus:
477     if (Lex.Lex() != tgtok::IntVal) {
478       TokError("expected integer value as end of range");
479       return true;
480     }
481     End = Lex.getCurIntVal();
482     break;
483   case tgtok::IntVal:
484     End = -Lex.getCurIntVal();
485     break;
486   }
487   if (End < 0) 
488     return TokError("invalid range, cannot be negative");
489   Lex.Lex();
490   
491   // Add to the range.
492   if (Start < End) {
493     for (; Start <= End; ++Start)
494       Ranges.push_back(Start);
495   } else {
496     for (; Start >= End; --Start)
497       Ranges.push_back(Start);
498   }
499   return false;
500 }
501
502 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
503 ///
504 ///   RangeList ::= RangePiece (',' RangePiece)*
505 ///
506 std::vector<unsigned> TGParser::ParseRangeList() {
507   std::vector<unsigned> Result;
508   
509   // Parse the first piece.
510   if (ParseRangePiece(Result))
511     return std::vector<unsigned>();
512   while (Lex.getCode() == tgtok::comma) {
513     Lex.Lex();  // Eat the comma.
514
515     // Parse the next range piece.
516     if (ParseRangePiece(Result))
517       return std::vector<unsigned>();
518   }
519   return Result;
520 }
521
522 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
523 ///   OptionalRangeList ::= '<' RangeList '>'
524 ///   OptionalRangeList ::= /*empty*/
525 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
526   if (Lex.getCode() != tgtok::less)
527     return false;
528   
529   TGLoc StartLoc = Lex.getLoc();
530   Lex.Lex(); // eat the '<'
531   
532   // Parse the range list.
533   Ranges = ParseRangeList();
534   if (Ranges.empty()) return true;
535   
536   if (Lex.getCode() != tgtok::greater) {
537     TokError("expected '>' at end of range list");
538     return Error(StartLoc, "to match this '<'");
539   }
540   Lex.Lex();   // eat the '>'.
541   return false;
542 }
543
544 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
545 ///   OptionalBitList ::= '{' RangeList '}'
546 ///   OptionalBitList ::= /*empty*/
547 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
548   if (Lex.getCode() != tgtok::l_brace)
549     return false;
550   
551   TGLoc StartLoc = Lex.getLoc();
552   Lex.Lex(); // eat the '{'
553   
554   // Parse the range list.
555   Ranges = ParseRangeList();
556   if (Ranges.empty()) return true;
557   
558   if (Lex.getCode() != tgtok::r_brace) {
559     TokError("expected '}' at end of bit list");
560     return Error(StartLoc, "to match this '{'");
561   }
562   Lex.Lex();   // eat the '}'.
563   return false;
564 }
565
566
567 /// ParseType - Parse and return a tblgen type.  This returns null on error.
568 ///
569 ///   Type ::= STRING                       // string type
570 ///   Type ::= BIT                          // bit type
571 ///   Type ::= BITS '<' INTVAL '>'          // bits<x> type
572 ///   Type ::= INT                          // int type
573 ///   Type ::= LIST '<' Type '>'            // list<x> type
574 ///   Type ::= CODE                         // code type
575 ///   Type ::= DAG                          // dag type
576 ///   Type ::= ClassID                      // Record Type
577 ///
578 RecTy *TGParser::ParseType() {
579   switch (Lex.getCode()) {
580   default: TokError("Unknown token when expecting a type"); return 0;
581   case tgtok::String: Lex.Lex(); return new StringRecTy();
582   case tgtok::Bit:    Lex.Lex(); return new BitRecTy();
583   case tgtok::Int:    Lex.Lex(); return new IntRecTy();
584   case tgtok::Code:   Lex.Lex(); return new CodeRecTy();
585   case tgtok::Dag:    Lex.Lex(); return new DagRecTy();
586   case tgtok::Id:
587     if (Record *R = ParseClassID()) return new RecordRecTy(R);
588     return 0;
589   case tgtok::Bits: {
590     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
591       TokError("expected '<' after bits type");
592       return 0;
593     }
594     if (Lex.Lex() != tgtok::IntVal) {  // Eat '<'
595       TokError("expected integer in bits<n> type");
596       return 0;
597     }
598     uint64_t Val = Lex.getCurIntVal();
599     if (Lex.Lex() != tgtok::greater) {  // Eat count.
600       TokError("expected '>' at end of bits<n> type");
601       return 0;
602     }
603     Lex.Lex();  // Eat '>'
604     return new BitsRecTy(Val);
605   }
606   case tgtok::List: {
607     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
608       TokError("expected '<' after list type");
609       return 0;
610     }
611     Lex.Lex();  // Eat '<'
612     RecTy *SubType = ParseType();
613     if (SubType == 0) return 0;
614     
615     if (Lex.getCode() != tgtok::greater) {
616       TokError("expected '>' at end of list<ty> type");
617       return 0;
618     }
619     Lex.Lex();  // Eat '>'
620     return new ListRecTy(SubType);
621   }
622   }      
623 }
624
625 /// ParseIDValue - Parse an ID as a value and decode what it means.
626 ///
627 ///  IDValue ::= ID [def local value]
628 ///  IDValue ::= ID [def template arg]
629 ///  IDValue ::= ID [multiclass local value]
630 ///  IDValue ::= ID [multiclass template argument]
631 ///  IDValue ::= ID [def name]
632 ///
633 Init *TGParser::ParseIDValue(Record *CurRec) {
634   assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
635   std::string Name = Lex.getCurStrVal();
636   TGLoc Loc = Lex.getLoc();
637   Lex.Lex();
638   return ParseIDValue(CurRec, Name, Loc);
639 }
640
641 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
642 /// has already been read.
643 Init *TGParser::ParseIDValue(Record *CurRec, 
644                              const std::string &Name, TGLoc NameLoc) {
645   if (CurRec) {
646     if (const RecordVal *RV = CurRec->getValue(Name))
647       return new VarInit(Name, RV->getType());
648     
649     std::string TemplateArgName = CurRec->getName()+":"+Name;
650     if (CurRec->isTemplateArg(TemplateArgName)) {
651       const RecordVal *RV = CurRec->getValue(TemplateArgName);
652       assert(RV && "Template arg doesn't exist??");
653       return new VarInit(TemplateArgName, RV->getType());
654     }
655   }
656   
657   if (CurMultiClass) {
658     std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
659     if (CurMultiClass->Rec.isTemplateArg(MCName)) {
660       const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
661       assert(RV && "Template arg doesn't exist??");
662       return new VarInit(MCName, RV->getType());
663     }
664   }
665   
666   if (Record *D = Records.getDef(Name))
667     return new DefInit(D);
668
669   Error(NameLoc, "Variable not defined: '" + Name + "'");
670   return 0;
671 }
672
673 /// ParseOperation - Parse an operator.  This returns null on error.
674 ///
675 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
676 ///
677 Init *TGParser::ParseOperation(Record *CurRec) {
678   switch (Lex.getCode()) {
679   default:
680     TokError("unknown operation");
681     return 0;
682     break;
683   case tgtok::XCar:
684   case tgtok::XCdr:
685   case tgtok::XNull:
686   case tgtok::XCast: {  // Value ::= !unop '(' Value ')'
687     UnOpInit::UnaryOp Code;
688     RecTy *Type = 0;
689
690     switch (Lex.getCode()) {
691     default: assert(0 && "Unhandled code!");
692     case tgtok::XCast:
693       Lex.Lex();  // eat the operation
694       Code = UnOpInit::CAST;
695
696       Type = ParseOperatorType();
697
698       if (Type == 0) {
699         TokError("did not get type for unary operator");
700         return 0;
701       }
702
703       break;
704     case tgtok::XCar:
705       Lex.Lex();  // eat the operation
706       Code = UnOpInit::CAR;
707       break;
708     case tgtok::XCdr:
709       Lex.Lex();  // eat the operation
710       Code = UnOpInit::CDR;
711       break;
712     case tgtok::XNull:
713       Lex.Lex();  // eat the operation
714       Code = UnOpInit::LNULL;
715       Type = new IntRecTy;
716       break;
717     }
718     if (Lex.getCode() != tgtok::l_paren) {
719       TokError("expected '(' after unary operator");
720       return 0;
721     }
722     Lex.Lex();  // eat the '('
723
724     Init *LHS = ParseValue(CurRec);
725     if (LHS == 0) return 0;
726
727     if (Code == UnOpInit::CAR
728         || Code == UnOpInit::CDR
729         || Code == UnOpInit::LNULL) {
730       ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
731       TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
732       if (LHSl == 0 && LHSt == 0) {
733         TokError("expected list type argument in unary operator");
734         return 0;
735       }
736       if (LHSt) {
737         ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
738         if (LType == 0) {
739           TokError("expected list type argumnet in unary operator");
740           return 0;
741         }
742       }
743
744       if (Code == UnOpInit::CAR
745           || Code == UnOpInit::CDR) {
746         if (LHSl && LHSl->getSize() == 0) {
747           TokError("empty list argument in unary operator");
748           return 0;
749         }
750         if (LHSl) {
751           Init *Item = LHSl->getElement(0);
752           TypedInit *Itemt = dynamic_cast<TypedInit*>(Item);
753           if (Itemt == 0) {
754             TokError("untyped list element in unary operator");
755             return 0;
756           }
757           if (Code == UnOpInit::CAR) {
758             Type = Itemt->getType();
759           }
760           else {
761             Type = new ListRecTy(Itemt->getType());
762           }
763         }
764         else {
765           assert(LHSt && "expected list type argument in unary operator");
766           ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
767           if (LType == 0) {
768             TokError("expected list type argumnet in unary operator");
769             return 0;
770           }
771           if (Code == UnOpInit::CAR) {
772             Type = LType->getElementType();
773           }
774           else {
775             Type = LType;
776           }
777         }
778       }
779     }
780
781     if (Lex.getCode() != tgtok::r_paren) {
782       TokError("expected ')' in unary operator");
783       return 0;
784     }
785     Lex.Lex();  // eat the ')'
786     return (new UnOpInit(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
787   }
788
789   case tgtok::XConcat:
790   case tgtok::XSRA: 
791   case tgtok::XSRL:
792   case tgtok::XSHL:
793   case tgtok::XStrConcat:
794   case tgtok::XNameConcat: {  // Value ::= !binop '(' Value ',' Value ')'
795     BinOpInit::BinaryOp Code;
796     RecTy *Type = 0;
797
798
799     switch (Lex.getCode()) {
800     default: assert(0 && "Unhandled code!");
801     case tgtok::XConcat:     
802       Lex.Lex();  // eat the operation
803       Code = BinOpInit::CONCAT;
804       Type = new DagRecTy();
805       break;
806     case tgtok::XSRA:        
807       Lex.Lex();  // eat the operation
808       Code = BinOpInit::SRA;
809       Type = new IntRecTy();
810       break;
811     case tgtok::XSRL:        
812       Lex.Lex();  // eat the operation
813       Code = BinOpInit::SRL;
814       Type = new IntRecTy();
815       break;
816     case tgtok::XSHL:        
817       Lex.Lex();  // eat the operation
818       Code = BinOpInit::SHL;
819       Type = new IntRecTy();
820       break;
821     case tgtok::XStrConcat:  
822       Lex.Lex();  // eat the operation
823       Code = BinOpInit::STRCONCAT;
824       Type = new StringRecTy();
825       break;
826     case tgtok::XNameConcat: 
827       Lex.Lex();  // eat the operation
828       Code = BinOpInit::NAMECONCAT;
829
830       Type = ParseOperatorType();
831
832       if (Type == 0) {
833         TokError("did not get type for binary operator");
834         return 0;
835       }
836
837       break;
838     }
839     if (Lex.getCode() != tgtok::l_paren) {
840       TokError("expected '(' after binary operator");
841       return 0;
842     }
843     Lex.Lex();  // eat the '('
844
845     Init *LHS = ParseValue(CurRec);
846     if (LHS == 0) return 0;
847
848     if (Lex.getCode() != tgtok::comma) {
849       TokError("expected ',' in binary operator");
850       return 0;
851     }
852     Lex.Lex();  // eat the ','
853     
854     Init *RHS = ParseValue(CurRec);
855     if (RHS == 0) return 0;
856
857     if (Lex.getCode() != tgtok::r_paren) {
858       TokError("expected ')' in binary operator");
859       return 0;
860     }
861     Lex.Lex();  // eat the ')'
862     return (new BinOpInit(Code, LHS, RHS, Type))->Fold(CurRec, CurMultiClass);
863   }
864
865   case tgtok::XIf:
866   case tgtok::XForEach:
867   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
868     TernOpInit::TernaryOp Code;
869     RecTy *Type = 0;
870
871
872     tgtok::TokKind LexCode = Lex.getCode();
873     Lex.Lex();  // eat the operation
874     switch (LexCode) {
875     default: assert(0 && "Unhandled code!");
876     case tgtok::XIf:
877       Code = TernOpInit::IF;
878       break;
879     case tgtok::XForEach:
880       Code = TernOpInit::FOREACH;
881       break;
882     case tgtok::XSubst:
883       Code = TernOpInit::SUBST;
884       break;
885     }
886     if (Lex.getCode() != tgtok::l_paren) {
887       TokError("expected '(' after ternary operator");
888       return 0;
889     }
890     Lex.Lex();  // eat the '('
891
892     Init *LHS = ParseValue(CurRec);
893     if (LHS == 0) return 0;
894
895     if (Lex.getCode() != tgtok::comma) {
896       TokError("expected ',' in ternary operator");
897       return 0;
898     }
899     Lex.Lex();  // eat the ','
900     
901     Init *MHS = ParseValue(CurRec);
902     if (MHS == 0) return 0;
903
904     if (Lex.getCode() != tgtok::comma) {
905       TokError("expected ',' in ternary operator");
906       return 0;
907     }
908     Lex.Lex();  // eat the ','
909     
910     Init *RHS = ParseValue(CurRec);
911     if (RHS == 0) return 0;
912
913     if (Lex.getCode() != tgtok::r_paren) {
914       TokError("expected ')' in binary operator");
915       return 0;
916     }
917     Lex.Lex();  // eat the ')'
918
919     switch (LexCode) {
920     default: assert(0 && "Unhandled code!");
921     case tgtok::XIf: {
922       TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
923       TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
924       if (MHSt == 0 || RHSt == 0) {
925         TokError("could not get type for !if");
926         return 0;
927       }
928       if (MHSt->getType()->typeIsConvertibleTo(RHSt->getType())) {
929         Type = RHSt->getType();
930       }
931       else if (RHSt->getType()->typeIsConvertibleTo(MHSt->getType())) {
932         Type = MHSt->getType();
933       }
934       else {
935         TokError("inconsistent types for !if");
936         return 0;
937       }
938       break;
939     }
940     case tgtok::XForEach: {
941       TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
942       if (MHSt == 0) {
943         TokError("could not get type for !foreach");
944         return 0;
945       }
946       Type = MHSt->getType();
947       break;
948     }
949     case tgtok::XSubst: {
950       TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
951       if (RHSt == 0) {
952         TokError("could not get type for !subst");
953         return 0;
954       }
955       Type = RHSt->getType();
956       break;
957     }
958     }
959     return (new TernOpInit(Code, LHS, MHS, RHS, Type))->Fold(CurRec, CurMultiClass);
960   }
961   }
962   TokError("could not parse operation");
963   return 0;
964 }
965
966 /// ParseOperatorType - Parse a type for an operator.  This returns
967 /// null on error.
968 ///
969 /// OperatorType ::= '<' Type '>'
970 ///
971 RecTy *TGParser::ParseOperatorType(void) {
972   RecTy *Type = 0;
973
974   if (Lex.getCode() != tgtok::less) {
975     TokError("expected type name for operator");
976     return 0;
977   }
978   Lex.Lex();  // eat the <
979
980   Type = ParseType();
981
982   if (Type == 0) {
983     TokError("expected type name for operator");
984     return 0;
985   }
986
987   if (Lex.getCode() != tgtok::greater) {
988     TokError("expected type name for operator");
989     return 0;
990   }
991   Lex.Lex();  // eat the >
992
993   return Type;
994 }
995
996
997 /// ParseSimpleValue - Parse a tblgen value.  This returns null on error.
998 ///
999 ///   SimpleValue ::= IDValue
1000 ///   SimpleValue ::= INTVAL
1001 ///   SimpleValue ::= STRVAL+
1002 ///   SimpleValue ::= CODEFRAGMENT
1003 ///   SimpleValue ::= '?'
1004 ///   SimpleValue ::= '{' ValueList '}'
1005 ///   SimpleValue ::= ID '<' ValueListNE '>'
1006 ///   SimpleValue ::= '[' ValueList ']'
1007 ///   SimpleValue ::= '(' IDValue DagArgList ')'
1008 ///   SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1009 ///   SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1010 ///   SimpleValue ::= SRATOK '(' Value ',' Value ')'
1011 ///   SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1012 ///   SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1013 ///
1014 Init *TGParser::ParseSimpleValue(Record *CurRec) {
1015   Init *R = 0;
1016   switch (Lex.getCode()) {
1017   default: TokError("Unknown token when parsing a value"); break;
1018   case tgtok::IntVal: R = new IntInit(Lex.getCurIntVal()); Lex.Lex(); break;
1019   case tgtok::StrVal: {
1020     std::string Val = Lex.getCurStrVal();
1021     Lex.Lex();
1022     
1023     // Handle multiple consecutive concatenated strings.
1024     while (Lex.getCode() == tgtok::StrVal) {
1025       Val += Lex.getCurStrVal();
1026       Lex.Lex();
1027     }
1028     
1029     R = new StringInit(Val);
1030     break;
1031   }
1032   case tgtok::CodeFragment:
1033       R = new CodeInit(Lex.getCurStrVal()); Lex.Lex(); break;
1034   case tgtok::question: R = new UnsetInit(); Lex.Lex(); break;
1035   case tgtok::Id: {
1036     TGLoc NameLoc = Lex.getLoc();
1037     std::string Name = Lex.getCurStrVal();
1038     if (Lex.Lex() != tgtok::less)  // consume the Id.
1039       return ParseIDValue(CurRec, Name, NameLoc);    // Value ::= IDValue
1040     
1041     // Value ::= ID '<' ValueListNE '>'
1042     if (Lex.Lex() == tgtok::greater) {
1043       TokError("expected non-empty value list");
1044       return 0;
1045     }
1046     std::vector<Init*> ValueList = ParseValueList(CurRec);
1047     if (ValueList.empty()) return 0;
1048     
1049     if (Lex.getCode() != tgtok::greater) {
1050       TokError("expected '>' at end of value list");
1051       return 0;
1052     }
1053     Lex.Lex();  // eat the '>'
1054     
1055     // This is a CLASS<initvalslist> expression.  This is supposed to synthesize
1056     // a new anonymous definition, deriving from CLASS<initvalslist> with no
1057     // body.
1058     Record *Class = Records.getClass(Name);
1059     if (!Class) {
1060       Error(NameLoc, "Expected a class name, got '" + Name + "'");
1061       return 0;
1062     }
1063     
1064     // Create the new record, set it as CurRec temporarily.
1065     static unsigned AnonCounter = 0;
1066     Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),NameLoc);
1067     SubClassReference SCRef;
1068     SCRef.RefLoc = NameLoc;
1069     SCRef.Rec = Class;
1070     SCRef.TemplateArgs = ValueList;
1071     // Add info about the subclass to NewRec.
1072     if (AddSubClass(NewRec, SCRef))
1073       return 0;
1074     NewRec->resolveReferences();
1075     Records.addDef(NewRec);
1076     
1077     // The result of the expression is a reference to the new record.
1078     return new DefInit(NewRec);
1079   }    
1080   case tgtok::l_brace: {           // Value ::= '{' ValueList '}'
1081     TGLoc BraceLoc = Lex.getLoc();
1082     Lex.Lex(); // eat the '{'
1083     std::vector<Init*> Vals;
1084     
1085     if (Lex.getCode() != tgtok::r_brace) {
1086       Vals = ParseValueList(CurRec);
1087       if (Vals.empty()) return 0;
1088     }
1089     if (Lex.getCode() != tgtok::r_brace) {
1090       TokError("expected '}' at end of bit list value");
1091       return 0;
1092     }
1093     Lex.Lex();  // eat the '}'
1094     
1095     BitsInit *Result = new BitsInit(Vals.size());
1096     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1097       Init *Bit = Vals[i]->convertInitializerTo(new BitRecTy());
1098       if (Bit == 0) {
1099         Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1100               ") is not convertable to a bit");
1101         return 0;
1102       }
1103       Result->setBit(Vals.size()-i-1, Bit);
1104     }
1105     return Result;
1106   }
1107   case tgtok::l_square: {          // Value ::= '[' ValueList ']'
1108     Lex.Lex(); // eat the '['
1109     std::vector<Init*> Vals;
1110     
1111     if (Lex.getCode() != tgtok::r_square) {
1112       Vals = ParseValueList(CurRec);
1113       if (Vals.empty()) return 0;
1114     }
1115     if (Lex.getCode() != tgtok::r_square) {
1116       TokError("expected ']' at end of list value");
1117       return 0;
1118     }
1119     Lex.Lex();  // eat the ']'
1120     return new ListInit(Vals);
1121   }
1122   case tgtok::l_paren: {         // Value ::= '(' IDValue DagArgList ')'
1123     Lex.Lex();   // eat the '('
1124     if (Lex.getCode() != tgtok::Id
1125         && Lex.getCode() != tgtok::XCast
1126         && Lex.getCode() != tgtok::XNameConcat) {
1127       TokError("expected identifier in dag init");
1128       return 0;
1129     }
1130     
1131     Init *Operator = 0;
1132     if (Lex.getCode() == tgtok::Id) {
1133       Operator = ParseIDValue(CurRec);
1134       if (Operator == 0) return 0;
1135     }
1136     else {
1137       Operator = ParseOperation(CurRec);
1138       if (Operator == 0) return 0;
1139     }
1140
1141     // If the operator name is present, parse it.
1142     std::string OperatorName;
1143     if (Lex.getCode() == tgtok::colon) {
1144       if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1145         TokError("expected variable name in dag operator");
1146         return 0;
1147       }
1148       OperatorName = Lex.getCurStrVal();
1149       Lex.Lex();  // eat the VarName.
1150     }
1151     
1152     std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1153     if (Lex.getCode() != tgtok::r_paren) {
1154       DagArgs = ParseDagArgList(CurRec);
1155       if (DagArgs.empty()) return 0;
1156     }
1157     
1158     if (Lex.getCode() != tgtok::r_paren) {
1159       TokError("expected ')' in dag init");
1160       return 0;
1161     }
1162     Lex.Lex();  // eat the ')'
1163     
1164     return new DagInit(Operator, OperatorName, DagArgs);
1165     break;
1166   }
1167  
1168   case tgtok::XCar:
1169   case tgtok::XCdr:
1170   case tgtok::XNull:
1171   case tgtok::XCast:  // Value ::= !unop '(' Value ')'
1172   case tgtok::XConcat:
1173   case tgtok::XSRA: 
1174   case tgtok::XSRL:
1175   case tgtok::XSHL:
1176   case tgtok::XStrConcat:
1177   case tgtok::XNameConcat:  // Value ::= !binop '(' Value ',' Value ')'
1178   case tgtok::XIf:
1179   case tgtok::XForEach:
1180   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1181     return ParseOperation(CurRec);
1182     break;
1183   }
1184   }
1185   
1186   return R;
1187 }
1188
1189 /// ParseValue - Parse a tblgen value.  This returns null on error.
1190 ///
1191 ///   Value       ::= SimpleValue ValueSuffix*
1192 ///   ValueSuffix ::= '{' BitList '}'
1193 ///   ValueSuffix ::= '[' BitList ']'
1194 ///   ValueSuffix ::= '.' ID
1195 ///
1196 Init *TGParser::ParseValue(Record *CurRec) {
1197   Init *Result = ParseSimpleValue(CurRec);
1198   if (Result == 0) return 0;
1199   
1200   // Parse the suffixes now if present.
1201   while (1) {
1202     switch (Lex.getCode()) {
1203     default: return Result;
1204     case tgtok::l_brace: {
1205       TGLoc CurlyLoc = Lex.getLoc();
1206       Lex.Lex(); // eat the '{'
1207       std::vector<unsigned> Ranges = ParseRangeList();
1208       if (Ranges.empty()) return 0;
1209       
1210       // Reverse the bitlist.
1211       std::reverse(Ranges.begin(), Ranges.end());
1212       Result = Result->convertInitializerBitRange(Ranges);
1213       if (Result == 0) {
1214         Error(CurlyLoc, "Invalid bit range for value");
1215         return 0;
1216       }
1217       
1218       // Eat the '}'.
1219       if (Lex.getCode() != tgtok::r_brace) {
1220         TokError("expected '}' at end of bit range list");
1221         return 0;
1222       }
1223       Lex.Lex();
1224       break;
1225     }
1226     case tgtok::l_square: {
1227       TGLoc SquareLoc = Lex.getLoc();
1228       Lex.Lex(); // eat the '['
1229       std::vector<unsigned> Ranges = ParseRangeList();
1230       if (Ranges.empty()) return 0;
1231       
1232       Result = Result->convertInitListSlice(Ranges);
1233       if (Result == 0) {
1234         Error(SquareLoc, "Invalid range for list slice");
1235         return 0;
1236       }
1237       
1238       // Eat the ']'.
1239       if (Lex.getCode() != tgtok::r_square) {
1240         TokError("expected ']' at end of list slice");
1241         return 0;
1242       }
1243       Lex.Lex();
1244       break;
1245     }
1246     case tgtok::period:
1247       if (Lex.Lex() != tgtok::Id) {  // eat the .
1248         TokError("expected field identifier after '.'");
1249         return 0;
1250       }
1251       if (!Result->getFieldType(Lex.getCurStrVal())) {
1252         TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1253                  Result->getAsString() + "'");
1254         return 0;
1255       }
1256       Result = new FieldInit(Result, Lex.getCurStrVal());
1257       Lex.Lex();  // eat field name
1258       break;
1259     }
1260   }
1261 }
1262
1263 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1264 ///
1265 ///    ParseDagArgList ::= Value (':' VARNAME)?
1266 ///    ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1267 std::vector<std::pair<llvm::Init*, std::string> > 
1268 TGParser::ParseDagArgList(Record *CurRec) {
1269   std::vector<std::pair<llvm::Init*, std::string> > Result;
1270   
1271   while (1) {
1272     Init *Val = ParseValue(CurRec);
1273     if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1274     
1275     // If the variable name is present, add it.
1276     std::string VarName;
1277     if (Lex.getCode() == tgtok::colon) {
1278       if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1279         TokError("expected variable name in dag literal");
1280         return std::vector<std::pair<llvm::Init*, std::string> >();
1281       }
1282       VarName = Lex.getCurStrVal();
1283       Lex.Lex();  // eat the VarName.
1284     }
1285     
1286     Result.push_back(std::make_pair(Val, VarName));
1287     
1288     if (Lex.getCode() != tgtok::comma) break;
1289     Lex.Lex(); // eat the ','    
1290   }
1291   
1292   return Result;
1293 }
1294
1295
1296 /// ParseValueList - Parse a comma separated list of values, returning them as a
1297 /// vector.  Note that this always expects to be able to parse at least one
1298 /// value.  It returns an empty list if this is not possible.
1299 ///
1300 ///   ValueList ::= Value (',' Value)
1301 ///
1302 std::vector<Init*> TGParser::ParseValueList(Record *CurRec) {
1303   std::vector<Init*> Result;
1304   Result.push_back(ParseValue(CurRec));
1305   if (Result.back() == 0) return std::vector<Init*>();
1306   
1307   while (Lex.getCode() == tgtok::comma) {
1308     Lex.Lex();  // Eat the comma
1309     
1310     Result.push_back(ParseValue(CurRec));
1311     if (Result.back() == 0) return std::vector<Init*>();
1312   }
1313   
1314   return Result;
1315 }
1316
1317
1318
1319 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1320 /// empty string on error.  This can happen in a number of different context's,
1321 /// including within a def or in the template args for a def (which which case
1322 /// CurRec will be non-null) and within the template args for a multiclass (in
1323 /// which case CurRec will be null, but CurMultiClass will be set).  This can
1324 /// also happen within a def that is within a multiclass, which will set both
1325 /// CurRec and CurMultiClass.
1326 ///
1327 ///  Declaration ::= FIELD? Type ID ('=' Value)?
1328 ///
1329 std::string TGParser::ParseDeclaration(Record *CurRec, 
1330                                        bool ParsingTemplateArgs) {
1331   // Read the field prefix if present.
1332   bool HasField = Lex.getCode() == tgtok::Field;
1333   if (HasField) Lex.Lex();
1334   
1335   RecTy *Type = ParseType();
1336   if (Type == 0) return "";
1337   
1338   if (Lex.getCode() != tgtok::Id) {
1339     TokError("Expected identifier in declaration");
1340     return "";
1341   }
1342   
1343   TGLoc IdLoc = Lex.getLoc();
1344   std::string DeclName = Lex.getCurStrVal();
1345   Lex.Lex();
1346   
1347   if (ParsingTemplateArgs) {
1348     if (CurRec) {
1349       DeclName = CurRec->getName() + ":" + DeclName;
1350     } else {
1351       assert(CurMultiClass);
1352     }
1353     if (CurMultiClass)
1354       DeclName = CurMultiClass->Rec.getName() + "::" + DeclName;
1355   }
1356   
1357   // Add the value.
1358   if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1359     return "";
1360   
1361   // If a value is present, parse it.
1362   if (Lex.getCode() == tgtok::equal) {
1363     Lex.Lex();
1364     TGLoc ValLoc = Lex.getLoc();
1365     Init *Val = ParseValue(CurRec);
1366     if (Val == 0 ||
1367         SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1368       return "";
1369   }
1370   
1371   return DeclName;
1372 }
1373
1374 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1375 /// sequence of template-declarations in <>'s.  If CurRec is non-null, these are
1376 /// template args for a def, which may or may not be in a multiclass.  If null,
1377 /// these are the template args for a multiclass.
1378 ///
1379 ///    TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1380 /// 
1381 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1382   assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1383   Lex.Lex(); // eat the '<'
1384   
1385   Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1386   
1387   // Read the first declaration.
1388   std::string TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1389   if (TemplArg.empty())
1390     return true;
1391   
1392   TheRecToAddTo->addTemplateArg(TemplArg);
1393   
1394   while (Lex.getCode() == tgtok::comma) {
1395     Lex.Lex(); // eat the ','
1396     
1397     // Read the following declarations.
1398     TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1399     if (TemplArg.empty())
1400       return true;
1401     TheRecToAddTo->addTemplateArg(TemplArg);
1402   }
1403   
1404   if (Lex.getCode() != tgtok::greater)
1405     return TokError("expected '>' at end of template argument list");
1406   Lex.Lex(); // eat the '>'.
1407   return false;
1408 }
1409
1410
1411 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1412 ///
1413 ///   BodyItem ::= Declaration ';'
1414 ///   BodyItem ::= LET ID OptionalBitList '=' Value ';'
1415 bool TGParser::ParseBodyItem(Record *CurRec) {
1416   if (Lex.getCode() != tgtok::Let) {
1417     if (ParseDeclaration(CurRec, false).empty()) 
1418       return true;
1419     
1420     if (Lex.getCode() != tgtok::semi)
1421       return TokError("expected ';' after declaration");
1422     Lex.Lex();
1423     return false;
1424   }
1425
1426   // LET ID OptionalRangeList '=' Value ';'
1427   if (Lex.Lex() != tgtok::Id)
1428     return TokError("expected field identifier after let");
1429   
1430   TGLoc IdLoc = Lex.getLoc();
1431   std::string FieldName = Lex.getCurStrVal();
1432   Lex.Lex();  // eat the field name.
1433   
1434   std::vector<unsigned> BitList;
1435   if (ParseOptionalBitList(BitList)) 
1436     return true;
1437   std::reverse(BitList.begin(), BitList.end());
1438   
1439   if (Lex.getCode() != tgtok::equal)
1440     return TokError("expected '=' in let expression");
1441   Lex.Lex();  // eat the '='.
1442   
1443   Init *Val = ParseValue(CurRec);
1444   if (Val == 0) return true;
1445   
1446   if (Lex.getCode() != tgtok::semi)
1447     return TokError("expected ';' after let expression");
1448   Lex.Lex();
1449   
1450   return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1451 }
1452
1453 /// ParseBody - Read the body of a class or def.  Return true on error, false on
1454 /// success.
1455 ///
1456 ///   Body     ::= ';'
1457 ///   Body     ::= '{' BodyList '}'
1458 ///   BodyList BodyItem*
1459 ///
1460 bool TGParser::ParseBody(Record *CurRec) {
1461   // If this is a null definition, just eat the semi and return.
1462   if (Lex.getCode() == tgtok::semi) {
1463     Lex.Lex();
1464     return false;
1465   }
1466   
1467   if (Lex.getCode() != tgtok::l_brace)
1468     return TokError("Expected ';' or '{' to start body");
1469   // Eat the '{'.
1470   Lex.Lex();
1471   
1472   while (Lex.getCode() != tgtok::r_brace)
1473     if (ParseBodyItem(CurRec))
1474       return true;
1475
1476   // Eat the '}'.
1477   Lex.Lex();
1478   return false;
1479 }
1480
1481 /// ParseObjectBody - Parse the body of a def or class.  This consists of an
1482 /// optional ClassList followed by a Body.  CurRec is the current def or class
1483 /// that is being parsed.
1484 ///
1485 ///   ObjectBody      ::= BaseClassList Body
1486 ///   BaseClassList   ::= /*empty*/
1487 ///   BaseClassList   ::= ':' BaseClassListNE
1488 ///   BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1489 ///
1490 bool TGParser::ParseObjectBody(Record *CurRec) {
1491   // If there is a baseclass list, read it.
1492   if (Lex.getCode() == tgtok::colon) {
1493     Lex.Lex();
1494     
1495     // Read all of the subclasses.
1496     SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1497     while (1) {
1498       // Check for error.
1499       if (SubClass.Rec == 0) return true;
1500      
1501       // Add it.
1502       if (AddSubClass(CurRec, SubClass))
1503         return true;
1504       
1505       if (Lex.getCode() != tgtok::comma) break;
1506       Lex.Lex(); // eat ','.
1507       SubClass = ParseSubClassReference(CurRec, false);
1508     }
1509   }
1510
1511   // Process any variables on the let stack.
1512   for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1513     for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1514       if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1515                    LetStack[i][j].Bits, LetStack[i][j].Value))
1516         return true;
1517   
1518   return ParseBody(CurRec);
1519 }
1520
1521
1522 /// ParseDef - Parse and return a top level or multiclass def, return the record
1523 /// corresponding to it.  This returns null on error.
1524 ///
1525 ///   DefInst ::= DEF ObjectName ObjectBody
1526 ///
1527 llvm::Record *TGParser::ParseDef(MultiClass *CurMultiClass) {
1528   TGLoc DefLoc = Lex.getLoc();
1529   assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1530   Lex.Lex();  // Eat the 'def' token.  
1531
1532   // Parse ObjectName and make a record for it.
1533   Record *CurRec = new Record(ParseObjectName(), DefLoc);
1534   
1535   if (!CurMultiClass) {
1536     // Top-level def definition.
1537     
1538     // Ensure redefinition doesn't happen.
1539     if (Records.getDef(CurRec->getName())) {
1540       Error(DefLoc, "def '" + CurRec->getName() + "' already defined");
1541       return 0;
1542     }
1543     Records.addDef(CurRec);
1544   } else {
1545     // Otherwise, a def inside a multiclass, add it to the multiclass.
1546     for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1547       if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
1548         Error(DefLoc, "def '" + CurRec->getName() +
1549               "' already defined in this multiclass!");
1550         return 0;
1551       }
1552     CurMultiClass->DefPrototypes.push_back(CurRec);
1553   }
1554   
1555   if (ParseObjectBody(CurRec))
1556     return 0;
1557   
1558   if (CurMultiClass == 0)  // Def's in multiclasses aren't really defs.
1559     CurRec->resolveReferences();
1560   
1561   // If ObjectBody has template arguments, it's an error.
1562   assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1563   return CurRec;
1564 }
1565
1566
1567 /// ParseClass - Parse a tblgen class definition.
1568 ///
1569 ///   ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1570 ///
1571 bool TGParser::ParseClass() {
1572   assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1573   Lex.Lex();
1574   
1575   if (Lex.getCode() != tgtok::Id)
1576     return TokError("expected class name after 'class' keyword");
1577   
1578   Record *CurRec = Records.getClass(Lex.getCurStrVal());
1579   if (CurRec) {
1580     // If the body was previously defined, this is an error.
1581     if (!CurRec->getValues().empty() ||
1582         !CurRec->getSuperClasses().empty() ||
1583         !CurRec->getTemplateArgs().empty())
1584       return TokError("Class '" + CurRec->getName() + "' already defined");
1585   } else {
1586     // If this is the first reference to this class, create and add it.
1587     CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc());
1588     Records.addClass(CurRec);
1589   }
1590   Lex.Lex(); // eat the name.
1591   
1592   // If there are template args, parse them.
1593   if (Lex.getCode() == tgtok::less)
1594     if (ParseTemplateArgList(CurRec))
1595       return true;
1596
1597   // Finally, parse the object body.
1598   return ParseObjectBody(CurRec);
1599 }
1600
1601 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1602 /// of LetRecords.
1603 ///
1604 ///   LetList ::= LetItem (',' LetItem)*
1605 ///   LetItem ::= ID OptionalRangeList '=' Value
1606 ///
1607 std::vector<LetRecord> TGParser::ParseLetList() {
1608   std::vector<LetRecord> Result;
1609   
1610   while (1) {
1611     if (Lex.getCode() != tgtok::Id) {
1612       TokError("expected identifier in let definition");
1613       return std::vector<LetRecord>();
1614     }
1615     std::string Name = Lex.getCurStrVal();
1616     TGLoc NameLoc = Lex.getLoc();
1617     Lex.Lex();  // Eat the identifier. 
1618
1619     // Check for an optional RangeList.
1620     std::vector<unsigned> Bits;
1621     if (ParseOptionalRangeList(Bits)) 
1622       return std::vector<LetRecord>();
1623     std::reverse(Bits.begin(), Bits.end());
1624     
1625     if (Lex.getCode() != tgtok::equal) {
1626       TokError("expected '=' in let expression");
1627       return std::vector<LetRecord>();
1628     }
1629     Lex.Lex();  // eat the '='.
1630     
1631     Init *Val = ParseValue(0);
1632     if (Val == 0) return std::vector<LetRecord>();
1633     
1634     // Now that we have everything, add the record.
1635     Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1636     
1637     if (Lex.getCode() != tgtok::comma)
1638       return Result;
1639     Lex.Lex();  // eat the comma.    
1640   }
1641 }
1642
1643 /// ParseTopLevelLet - Parse a 'let' at top level.  This can be a couple of
1644 /// different related productions.
1645 ///
1646 ///   Object ::= LET LetList IN '{' ObjectList '}'
1647 ///   Object ::= LET LetList IN Object
1648 ///
1649 bool TGParser::ParseTopLevelLet() {
1650   assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1651   Lex.Lex();
1652   
1653   // Add this entry to the let stack.
1654   std::vector<LetRecord> LetInfo = ParseLetList();
1655   if (LetInfo.empty()) return true;
1656   LetStack.push_back(LetInfo);
1657
1658   if (Lex.getCode() != tgtok::In)
1659     return TokError("expected 'in' at end of top-level 'let'");
1660   Lex.Lex();
1661   
1662   // If this is a scalar let, just handle it now
1663   if (Lex.getCode() != tgtok::l_brace) {
1664     // LET LetList IN Object
1665     if (ParseObject())
1666       return true;
1667   } else {   // Object ::= LETCommand '{' ObjectList '}'
1668     TGLoc BraceLoc = Lex.getLoc();
1669     // Otherwise, this is a group let.
1670     Lex.Lex();  // eat the '{'.
1671     
1672     // Parse the object list.
1673     if (ParseObjectList())
1674       return true;
1675     
1676     if (Lex.getCode() != tgtok::r_brace) {
1677       TokError("expected '}' at end of top level let command");
1678       return Error(BraceLoc, "to match this '{'");
1679     }
1680     Lex.Lex();
1681   }
1682   
1683   // Outside this let scope, this let block is not active.
1684   LetStack.pop_back();
1685   return false;
1686 }
1687
1688 /// ParseMultiClassDef - Parse a def in a multiclass context.
1689 ///
1690 ///  MultiClassDef ::= DefInst
1691 ///
1692 bool TGParser::ParseMultiClassDef(MultiClass *CurMC) {
1693   if (Lex.getCode() != tgtok::Def) 
1694     return TokError("expected 'def' in multiclass body");
1695
1696   Record *D = ParseDef(CurMC);
1697   if (D == 0) return true;
1698   
1699   // Copy the template arguments for the multiclass into the def.
1700   const std::vector<std::string> &TArgs = CurMC->Rec.getTemplateArgs();
1701   
1702   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1703     const RecordVal *RV = CurMC->Rec.getValue(TArgs[i]);
1704     assert(RV && "Template arg doesn't exist?");
1705     D->addValue(*RV);
1706   }
1707
1708   return false;
1709 }
1710
1711 /// ParseMultiClass - Parse a multiclass definition.
1712 ///
1713 ///  MultiClassInst ::= MULTICLASS ID TemplateArgList?
1714 ///                     ':' BaseMultiClassList '{' MultiClassDef+ '}'
1715 ///
1716 bool TGParser::ParseMultiClass() {
1717   assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1718   Lex.Lex();  // Eat the multiclass token.
1719
1720   if (Lex.getCode() != tgtok::Id)
1721     return TokError("expected identifier after multiclass for name");
1722   std::string Name = Lex.getCurStrVal();
1723   
1724   if (MultiClasses.count(Name))
1725     return TokError("multiclass '" + Name + "' already defined");
1726   
1727   CurMultiClass = MultiClasses[Name] = new MultiClass(Name, Lex.getLoc());
1728   Lex.Lex();  // Eat the identifier.
1729   
1730   // If there are template args, parse them.
1731   if (Lex.getCode() == tgtok::less)
1732     if (ParseTemplateArgList(0))
1733       return true;
1734
1735   bool inherits = false;
1736
1737   // If there are submulticlasses, parse them.
1738   if (Lex.getCode() == tgtok::colon) {
1739     inherits = true;
1740
1741     Lex.Lex();
1742
1743     // Read all of the submulticlasses.
1744     SubMultiClassReference SubMultiClass =
1745       ParseSubMultiClassReference(CurMultiClass);
1746     while (1) {
1747       // Check for error.
1748       if (SubMultiClass.MC == 0) return true;
1749
1750       // Add it.
1751       if (AddSubMultiClass(CurMultiClass, SubMultiClass))
1752         return true;
1753
1754       if (Lex.getCode() != tgtok::comma) break;
1755       Lex.Lex(); // eat ','.
1756       SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1757     }
1758   }
1759
1760   if (Lex.getCode() != tgtok::l_brace) {
1761     if (!inherits)
1762       return TokError("expected '{' in multiclass definition");
1763     else
1764       if (Lex.getCode() != tgtok::semi)
1765         return TokError("expected ';' in multiclass definition");
1766       else
1767         Lex.Lex();  // eat the ';'.
1768   }
1769   else {
1770     if (Lex.Lex() == tgtok::r_brace)  // eat the '{'.
1771       return TokError("multiclass must contain at least one def");
1772   
1773     while (Lex.getCode() != tgtok::r_brace)
1774       if (ParseMultiClassDef(CurMultiClass))
1775         return true;
1776   
1777     Lex.Lex();  // eat the '}'.
1778   }
1779   
1780   CurMultiClass = 0;
1781   return false;
1782 }
1783
1784 /// ParseDefm - Parse the instantiation of a multiclass.
1785 ///
1786 ///   DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
1787 ///
1788 bool TGParser::ParseDefm() {
1789   assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
1790   if (Lex.Lex() != tgtok::Id)  // eat the defm.
1791     return TokError("expected identifier after defm");
1792   
1793   TGLoc DefmPrefixLoc = Lex.getLoc();
1794   std::string DefmPrefix = Lex.getCurStrVal();
1795   if (Lex.Lex() != tgtok::colon)
1796     return TokError("expected ':' after defm identifier");
1797   
1798   // eat the colon.
1799   Lex.Lex();
1800
1801   TGLoc SubClassLoc = Lex.getLoc();
1802   SubClassReference Ref = ParseSubClassReference(0, true);
1803
1804   while (1) {
1805     if (Ref.Rec == 0) return true;
1806
1807     // To instantiate a multiclass, we need to first get the multiclass, then
1808     // instantiate each def contained in the multiclass with the SubClassRef
1809     // template parameters.
1810     MultiClass *MC = MultiClasses[Ref.Rec->getName()];
1811     assert(MC && "Didn't lookup multiclass correctly?");
1812     std::vector<Init*> &TemplateVals = Ref.TemplateArgs;   
1813
1814     // Verify that the correct number of template arguments were specified.
1815     const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
1816     if (TArgs.size() < TemplateVals.size())
1817       return Error(SubClassLoc,
1818                    "more template args specified than multiclass expects");
1819
1820     // Loop over all the def's in the multiclass, instantiating each one.
1821     for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
1822       Record *DefProto = MC->DefPrototypes[i];
1823
1824       // Add in the defm name
1825       std::string DefName = DefProto->getName();
1826       std::string::size_type idx = DefName.find("#NAME#");
1827       if (idx != std::string::npos) {
1828         DefName.replace(idx, 6, DefmPrefix);
1829       }
1830       else {
1831         // Add the suffix to the defm name to get the new name.
1832         DefName = DefmPrefix + DefName;
1833       }
1834
1835       Record *CurRec = new Record(DefName, DefmPrefixLoc);
1836
1837       SubClassReference Ref;
1838       Ref.RefLoc = DefmPrefixLoc;
1839       Ref.Rec = DefProto;
1840       AddSubClass(CurRec, Ref);
1841
1842       // Loop over all of the template arguments, setting them to the specified
1843       // value or leaving them as the default if necessary.
1844       for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1845         // Check if a value is specified for this temp-arg.
1846         if (i < TemplateVals.size()) {
1847           // Set it now.
1848           if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1849                        TemplateVals[i]))
1850             return true;
1851
1852           // Resolve it next.
1853           CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1854
1855           // Now remove it.
1856           CurRec->removeValue(TArgs[i]);
1857
1858         } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
1859           return Error(SubClassLoc,
1860                        "value not specified for template argument #"+
1861                        utostr(i) + " (" + TArgs[i] + ") of multiclassclass '" +
1862                        MC->Rec.getName() + "'");
1863         }
1864       }
1865
1866       // If the mdef is inside a 'let' expression, add to each def.
1867       for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1868         for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1869           if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1870                        LetStack[i][j].Bits, LetStack[i][j].Value)) {
1871             Error(DefmPrefixLoc, "when instantiating this defm");
1872             return true;
1873           }
1874
1875       // Ensure redefinition doesn't happen.
1876       if (Records.getDef(CurRec->getName()))
1877         return Error(DefmPrefixLoc, "def '" + CurRec->getName() + 
1878                      "' already defined, instantiating defm with subdef '" + 
1879                      DefProto->getName() + "'");
1880       Records.addDef(CurRec);
1881       CurRec->resolveReferences();
1882     }
1883
1884     if (Lex.getCode() != tgtok::comma) break;
1885     Lex.Lex(); // eat ','.
1886
1887     SubClassLoc = Lex.getLoc();
1888     Ref = ParseSubClassReference(0, true);
1889   }
1890
1891   if (Lex.getCode() != tgtok::semi)
1892     return TokError("expected ';' at end of defm");
1893   Lex.Lex();
1894   
1895   return false;
1896 }
1897
1898 /// ParseObject
1899 ///   Object ::= ClassInst
1900 ///   Object ::= DefInst
1901 ///   Object ::= MultiClassInst
1902 ///   Object ::= DefMInst
1903 ///   Object ::= LETCommand '{' ObjectList '}'
1904 ///   Object ::= LETCommand Object
1905 bool TGParser::ParseObject() {
1906   switch (Lex.getCode()) {
1907   default: assert(0 && "This is not an object");
1908   case tgtok::Let:   return ParseTopLevelLet();
1909   case tgtok::Def:   return ParseDef(0) == 0;
1910   case tgtok::Defm:  return ParseDefm();
1911   case tgtok::Class: return ParseClass();
1912   case tgtok::MultiClass: return ParseMultiClass();
1913   }
1914 }
1915
1916 /// ParseObjectList
1917 ///   ObjectList :== Object*
1918 bool TGParser::ParseObjectList() {
1919   while (isObjectStart(Lex.getCode())) {
1920     if (ParseObject())
1921       return true;
1922   }
1923   return false;
1924 }
1925
1926
1927 bool TGParser::ParseFile() {
1928   Lex.Lex(); // Prime the lexer.
1929   if (ParseObjectList()) return true;
1930   
1931   // If we have unread input at the end of the file, report it.
1932   if (Lex.getCode() == tgtok::Eof)
1933     return false;
1934   
1935   return TokError("Unexpected input at top level");
1936 }
1937