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