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