Make IntInits and ListInits typed. This helps deduce types of !if and
[oota-llvm.git] / utils / TableGen / TGParser.cpp
1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implement the Parser for TableGen.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include <algorithm>
15 #include <sstream>
16
17 #include "TGParser.h"
18 #include "Record.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Support/Streams.h"
21 using namespace llvm;
22
23 //===----------------------------------------------------------------------===//
24 // Support Code for the Semantic Actions.
25 //===----------------------------------------------------------------------===//
26
27 namespace llvm {
28 struct SubClassReference {
29   TGLoc RefLoc;
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   TGLoc RefLoc;
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   cerr << "Multiclass:\n";
49  
50   MC->dump();
51  
52   cerr << "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, TGLoc Loc, const RecordVal &RV) {
64   if (CurRec == 0)
65     CurRec = &CurMultiClass->Rec;
66   
67   if (RecordVal *ERV = CurRec->getValue(RV.getName())) {
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, TGLoc Loc, const std::string &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 + "' unknown!");
91
92   // Do not allow assignments like 'X = X'.  This will just cause infinite loops
93   // in the resolution machinery.
94   if (BitList.empty())
95     if (VarInit *VI = dynamic_cast<VarInit*>(V))
96       if (VI->getName() == ValName)
97         return false;
98   
99   // If we are assigning to a subset of the bits in the value... then we must be
100   // assigning to a field of BitsRecTy, which must have a BitsInit
101   // initializer.
102   //
103   if (!BitList.empty()) {
104     BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
105     if (CurVal == 0)
106       return Error(Loc, "Value '" + ValName + "' is not a bits type");
107
108     // Convert the incoming value to a bits type of the appropriate size...
109     Init *BI = V->convertInitializerTo(new BitsRecTy(BitList.size()));
110     if (BI == 0) {
111       V->convertInitializerTo(new BitsRecTy(BitList.size()));
112       return Error(Loc, "Initializer is not compatible with bit range");
113     }
114                    
115     // We should have a BitsInit type now.
116     BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
117     assert(BInit != 0);
118
119     BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
120
121     // Loop over bits, assigning values as appropriate.
122     for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
123       unsigned Bit = BitList[i];
124       if (NewVal->getBit(Bit))
125         return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
126                      ValName + "' more than once");
127       NewVal->setBit(Bit, BInit->getBit(i));
128     }
129
130     for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
131       if (NewVal->getBit(i) == 0)
132         NewVal->setBit(i, CurVal->getBit(i));
133
134     V = NewVal;
135   }
136
137   if (RV->setValue(V))
138    return Error(Loc, "Value '" + ValName + "' of type '" + 
139                 RV->getType()->getAsString() + 
140                 "' is incompatible with initializer '" + V->getAsString() +"'");
141   return false;
142 }
143
144 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
145 /// args as SubClass's template arguments.
146 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
147   Record *SC = SubClass.Rec;
148   // Add all of the values in the subclass into the current class.
149   const std::vector<RecordVal> &Vals = SC->getValues();
150   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
151     if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
152       return true;
153
154   const std::vector<std::string> &TArgs = SC->getTemplateArgs();
155
156   // Ensure that an appropriate number of template arguments are specified.
157   if (TArgs.size() < SubClass.TemplateArgs.size())
158     return Error(SubClass.RefLoc, "More template args specified than expected");
159   
160   // Loop over all of the template arguments, setting them to the specified
161   // value or leaving them as the default if necessary.
162   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
163     if (i < SubClass.TemplateArgs.size()) {
164       // If a value is specified for this template arg, set it now.
165       if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(), 
166                    SubClass.TemplateArgs[i]))
167         return true;
168       
169       // Resolve it next.
170       CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
171       
172       // Now remove it.
173       CurRec->removeValue(TArgs[i]);
174
175     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
176       return Error(SubClass.RefLoc,"Value not specified for template argument #"
177                    + utostr(i) + " (" + TArgs[i] + ") of subclass '" + 
178                    SC->getName() + "'!");
179     }
180   }
181
182   // Since everything went well, we can now set the "superclass" list for the
183   // current record.
184   const std::vector<Record*> &SCs = SC->getSuperClasses();
185   for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
186     if (CurRec->isSubClassOf(SCs[i]))
187       return Error(SubClass.RefLoc,
188                    "Already subclass of '" + SCs[i]->getName() + "'!\n");
189     CurRec->addSuperClass(SCs[i]);
190   }
191   
192   if (CurRec->isSubClassOf(SC))
193     return Error(SubClass.RefLoc,
194                  "Already subclass of '" + SC->getName() + "'!\n");
195   CurRec->addSuperClass(SC);
196   return false;
197 }
198
199 /// AddSubMultiClass - Add SubMultiClass as a subclass to
200 /// CurMC, resolving its template args as SubMultiClass's
201 /// template arguments.
202 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
203                                 SubMultiClassReference &SubMultiClass) {
204   MultiClass *SMC = SubMultiClass.MC;
205   Record *CurRec = &CurMC->Rec;
206
207   const std::vector<RecordVal> &MCVals = CurRec->getValues();
208
209   // Add all of the values in the subclass into the current class.
210   const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
211   for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
212     if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
213       return true;
214
215   int newDefStart = CurMC->DefPrototypes.size();
216
217   // Add all of the defs in the subclass into the current multiclass.
218   for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
219          iend = SMC->DefPrototypes.end();
220        i != iend;
221        ++i) {
222     // Clone the def and add it to the current multiclass
223     Record *NewDef = new Record(**i);
224
225     // Add all of the values in the superclass into the current def.
226     for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
227       if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
228         return true;
229
230     CurMC->DefPrototypes.push_back(NewDef);
231   }
232
233   const std::vector<std::string> &SMCTArgs = SMC->Rec.getTemplateArgs();
234
235   // Ensure that an appropriate number of template arguments are
236   // specified.
237   if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
238     return Error(SubMultiClass.RefLoc,
239                  "More template args specified than expected");
240
241   // Loop over all of the template arguments, setting them to the specified
242   // value or leaving them as the default if necessary.
243   for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
244     if (i < SubMultiClass.TemplateArgs.size()) {
245       // If a value is specified for this template arg, set it in the
246       // superclass now.
247       if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i],
248                    std::vector<unsigned>(),
249                    SubMultiClass.TemplateArgs[i]))
250         return true;
251
252       // Resolve it next.
253       CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
254
255       // Now remove it.
256       CurRec->removeValue(SMCTArgs[i]);
257
258       // If a value is specified for this template arg, set it in the
259       // new defs now.
260       for (MultiClass::RecordVector::iterator j =
261              CurMC->DefPrototypes.begin() + newDefStart,
262              jend = CurMC->DefPrototypes.end();
263            j != jend;
264            ++j) {
265         Record *Def = *j;
266
267         if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i],
268                      std::vector<unsigned>(),
269                      SubMultiClass.TemplateArgs[i]))
270           return true;
271
272         // Resolve it next.
273         Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
274
275         // Now remove it
276         Def->removeValue(SMCTArgs[i]);
277       }
278     } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
279       return Error(SubMultiClass.RefLoc,
280                    "Value not specified for template argument #"
281                    + utostr(i) + " (" + SMCTArgs[i] + ") of subclass '" +
282                    SMC->Rec.getName() + "'!");
283     }
284   }
285
286   return false;
287 }
288
289 //===----------------------------------------------------------------------===//
290 // Parser Code
291 //===----------------------------------------------------------------------===//
292
293 /// isObjectStart - Return true if this is a valid first token for an Object.
294 static bool isObjectStart(tgtok::TokKind K) {
295   return K == tgtok::Class || K == tgtok::Def ||
296          K == tgtok::Defm || K == tgtok::Let || K == tgtok::MultiClass; 
297 }
298
299 /// ParseObjectName - If an object name is specified, return it.  Otherwise,
300 /// return an anonymous name.
301 ///   ObjectName ::= ID
302 ///   ObjectName ::= /*empty*/
303 ///
304 std::string TGParser::ParseObjectName() {
305   if (Lex.getCode() == tgtok::Id) {
306     std::string Ret = Lex.getCurStrVal();
307     Lex.Lex();
308     return Ret;
309   }
310   
311   static unsigned AnonCounter = 0;
312   return "anonymous."+utostr(AnonCounter++);
313 }
314
315
316 /// ParseClassID - Parse and resolve a reference to a class name.  This returns
317 /// null on error.
318 ///
319 ///    ClassID ::= ID
320 ///
321 Record *TGParser::ParseClassID() {
322   if (Lex.getCode() != tgtok::Id) {
323     TokError("expected name for ClassID");
324     return 0;
325   }
326   
327   Record *Result = Records.getClass(Lex.getCurStrVal());
328   if (Result == 0)
329     TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
330   
331   Lex.Lex();
332   return Result;
333 }
334
335 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
336 /// This returns null on error.
337 ///
338 ///    MultiClassID ::= ID
339 ///
340 MultiClass *TGParser::ParseMultiClassID() {
341   if (Lex.getCode() != tgtok::Id) {
342     TokError("expected name for ClassID");
343     return 0;
344   }
345
346   MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
347   if (Result == 0)
348     TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
349
350   Lex.Lex();
351   return Result;
352 }
353
354 Record *TGParser::ParseDefmID() {
355   if (Lex.getCode() != tgtok::Id) {
356     TokError("expected multiclass name");
357     return 0;
358   }
359   
360   MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
361   if (MC == 0) {
362     TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
363     return 0;
364   }
365   
366   Lex.Lex();
367   return &MC->Rec;
368 }  
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   TGLoc 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   TGLoc 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   TGLoc 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, TGLoc 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           }
768           else {
769             Type = new ListRecTy(Itemt->getType());
770           }
771         }
772         else {
773           assert(LHSt && "expected list type argument in unary operator");
774           ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
775           if (LType == 0) {
776             TokError("expected list type argumnet in unary operator");
777             return 0;
778           }
779           if (Code == UnOpInit::CAR) {
780             Type = LType->getElementType();
781           }
782           else {
783             Type = LType;
784           }
785         }
786       }
787     }
788
789     if (Lex.getCode() != tgtok::r_paren) {
790       TokError("expected ')' in unary operator");
791       return 0;
792     }
793     Lex.Lex();  // eat the ')'
794     return (new UnOpInit(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
795   }
796
797   case tgtok::XConcat:
798   case tgtok::XSRA: 
799   case tgtok::XSRL:
800   case tgtok::XSHL:
801   case tgtok::XStrConcat:
802   case tgtok::XRegMatch:
803   case tgtok::XNameConcat: {  // Value ::= !binop '(' Value ',' Value ')'
804     BinOpInit::BinaryOp Code;
805     RecTy *Type = 0;
806
807
808     switch (Lex.getCode()) {
809     default: assert(0 && "Unhandled code!");
810     case tgtok::XConcat:     
811       Lex.Lex();  // eat the operation
812       Code = BinOpInit::CONCAT;
813       Type = new DagRecTy();
814       break;
815     case tgtok::XSRA:        
816       Lex.Lex();  // eat the operation
817       Code = BinOpInit::SRA;
818       Type = new IntRecTy();
819       break;
820     case tgtok::XSRL:        
821       Lex.Lex();  // eat the operation
822       Code = BinOpInit::SRL;
823       Type = new IntRecTy();
824       break;
825     case tgtok::XSHL:        
826       Lex.Lex();  // eat the operation
827       Code = BinOpInit::SHL;
828       Type = new IntRecTy();
829       break;
830     case tgtok::XStrConcat:  
831       Lex.Lex();  // eat the operation
832       Code = BinOpInit::STRCONCAT;
833       Type = new StringRecTy();
834       break;
835     case tgtok::XRegMatch:  
836       Lex.Lex();  // eat the operation
837       Code = BinOpInit::REGMATCH;
838       Type = new IntRecTy();
839       break;
840     case tgtok::XNameConcat: 
841       Lex.Lex();  // eat the operation
842       Code = BinOpInit::NAMECONCAT;
843
844       Type = ParseOperatorType();
845
846       if (Type == 0) {
847         TokError("did not get type for binary operator");
848         return 0;
849       }
850
851       break;
852     }
853     if (Lex.getCode() != tgtok::l_paren) {
854       TokError("expected '(' after binary operator");
855       return 0;
856     }
857     Lex.Lex();  // eat the '('
858
859     Init *LHS = ParseValue(CurRec);
860     if (LHS == 0) return 0;
861
862     if (Lex.getCode() != tgtok::comma) {
863       TokError("expected ',' in binary operator");
864       return 0;
865     }
866     Lex.Lex();  // eat the ','
867     
868     Init *RHS = ParseValue(CurRec);
869     if (RHS == 0) return 0;
870
871     if (Lex.getCode() != tgtok::r_paren) {
872       TokError("expected ')' in binary operator");
873       return 0;
874     }
875     Lex.Lex();  // eat the ')'
876     return (new BinOpInit(Code, LHS, RHS, Type))->Fold(CurRec, CurMultiClass);
877   }
878
879   case tgtok::XIf:
880   case tgtok::XForEach:
881   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
882     TernOpInit::TernaryOp Code;
883     RecTy *Type = 0;
884
885
886     tgtok::TokKind LexCode = Lex.getCode();
887     Lex.Lex();  // eat the operation
888     switch (LexCode) {
889     default: assert(0 && "Unhandled code!");
890     case tgtok::XIf:
891       Code = TernOpInit::IF;
892       break;
893     case tgtok::XForEach:
894       Code = TernOpInit::FOREACH;
895       break;
896     case tgtok::XSubst:
897       Code = TernOpInit::SUBST;
898       break;
899     }
900     if (Lex.getCode() != tgtok::l_paren) {
901       TokError("expected '(' after ternary operator");
902       return 0;
903     }
904     Lex.Lex();  // eat the '('
905
906     Init *LHS = ParseValue(CurRec);
907     if (LHS == 0) return 0;
908
909     if (Lex.getCode() != tgtok::comma) {
910       TokError("expected ',' in ternary operator");
911       return 0;
912     }
913     Lex.Lex();  // eat the ','
914     
915     Init *MHS = ParseValue(CurRec);
916     if (MHS == 0) return 0;
917
918     if (Lex.getCode() != tgtok::comma) {
919       TokError("expected ',' in ternary operator");
920       return 0;
921     }
922     Lex.Lex();  // eat the ','
923     
924     Init *RHS = ParseValue(CurRec);
925     if (RHS == 0) return 0;
926
927     if (Lex.getCode() != tgtok::r_paren) {
928       TokError("expected ')' in binary operator");
929       return 0;
930     }
931     Lex.Lex();  // eat the ')'
932
933     switch (LexCode) {
934     default: assert(0 && "Unhandled code!");
935     case tgtok::XIf: {
936       TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
937       TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
938       if (MHSt == 0 || RHSt == 0) {
939         TokError("could not get type for !if");
940         return 0;
941       }
942       if (MHSt->getType()->typeIsConvertibleTo(RHSt->getType())) {
943         Type = RHSt->getType();
944       }
945       else if (RHSt->getType()->typeIsConvertibleTo(MHSt->getType())) {
946         Type = MHSt->getType();
947       }
948       else {
949         TokError("inconsistent types for !if");
950         return 0;
951       }
952       break;
953     }
954     case tgtok::XForEach: {
955       TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
956       if (MHSt == 0) {
957         TokError("could not get type for !foreach");
958         return 0;
959       }
960       Type = MHSt->getType();
961       break;
962     }
963     case tgtok::XSubst: {
964       TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
965       if (RHSt == 0) {
966         TokError("could not get type for !subst");
967         return 0;
968       }
969       Type = RHSt->getType();
970       break;
971     }
972     }
973     return (new TernOpInit(Code, LHS, MHS, RHS, Type))->Fold(CurRec, CurMultiClass);
974   }
975   }
976   TokError("could not parse operation");
977   return 0;
978 }
979
980 /// ParseOperatorType - Parse a type for an operator.  This returns
981 /// null on error.
982 ///
983 /// OperatorType ::= '<' Type '>'
984 ///
985 RecTy *TGParser::ParseOperatorType(void) {
986   RecTy *Type = 0;
987
988   if (Lex.getCode() != tgtok::less) {
989     TokError("expected type name for operator");
990     return 0;
991   }
992   Lex.Lex();  // eat the <
993
994   Type = ParseType();
995
996   if (Type == 0) {
997     TokError("expected type name for operator");
998     return 0;
999   }
1000
1001   if (Lex.getCode() != tgtok::greater) {
1002     TokError("expected type name for operator");
1003     return 0;
1004   }
1005   Lex.Lex();  // eat the >
1006
1007   return Type;
1008 }
1009
1010
1011 /// ParseSimpleValue - Parse a tblgen value.  This returns null on error.
1012 ///
1013 ///   SimpleValue ::= IDValue
1014 ///   SimpleValue ::= INTVAL
1015 ///   SimpleValue ::= STRVAL+
1016 ///   SimpleValue ::= CODEFRAGMENT
1017 ///   SimpleValue ::= '?'
1018 ///   SimpleValue ::= '{' ValueList '}'
1019 ///   SimpleValue ::= ID '<' ValueListNE '>'
1020 ///   SimpleValue ::= '[' ValueList ']'
1021 ///   SimpleValue ::= '(' IDValue DagArgList ')'
1022 ///   SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1023 ///   SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1024 ///   SimpleValue ::= SRATOK '(' Value ',' Value ')'
1025 ///   SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1026 ///   SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1027 ///
1028 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType) {
1029   Init *R = 0;
1030   switch (Lex.getCode()) {
1031   default: TokError("Unknown token when parsing a value"); break;
1032   case tgtok::IntVal: R = new IntInit(Lex.getCurIntVal()); Lex.Lex(); break;
1033   case tgtok::StrVal: {
1034     std::string Val = Lex.getCurStrVal();
1035     Lex.Lex();
1036     
1037     // Handle multiple consecutive concatenated strings.
1038     while (Lex.getCode() == tgtok::StrVal) {
1039       Val += Lex.getCurStrVal();
1040       Lex.Lex();
1041     }
1042     
1043     R = new StringInit(Val);
1044     break;
1045   }
1046   case tgtok::CodeFragment:
1047       R = new CodeInit(Lex.getCurStrVal()); Lex.Lex(); break;
1048   case tgtok::question: R = new UnsetInit(); Lex.Lex(); break;
1049   case tgtok::Id: {
1050     TGLoc NameLoc = Lex.getLoc();
1051     std::string Name = Lex.getCurStrVal();
1052     if (Lex.Lex() != tgtok::less)  // consume the Id.
1053       return ParseIDValue(CurRec, Name, NameLoc);    // Value ::= IDValue
1054     
1055     // Value ::= ID '<' ValueListNE '>'
1056     if (Lex.Lex() == tgtok::greater) {
1057       TokError("expected non-empty value list");
1058       return 0;
1059     }
1060
1061     // This is a CLASS<initvalslist> expression.  This is supposed to synthesize
1062     // a new anonymous definition, deriving from CLASS<initvalslist> with no
1063     // body.
1064     Record *Class = Records.getClass(Name);
1065     if (!Class) {
1066       Error(NameLoc, "Expected a class name, got '" + Name + "'");
1067       return 0;
1068     }
1069
1070     std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1071     if (ValueList.empty()) return 0;
1072     
1073     if (Lex.getCode() != tgtok::greater) {
1074       TokError("expected '>' at end of value list");
1075       return 0;
1076     }
1077     Lex.Lex();  // eat the '>'
1078     
1079     // Create the new record, set it as CurRec temporarily.
1080     static unsigned AnonCounter = 0;
1081     Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),NameLoc);
1082     SubClassReference SCRef;
1083     SCRef.RefLoc = NameLoc;
1084     SCRef.Rec = Class;
1085     SCRef.TemplateArgs = ValueList;
1086     // Add info about the subclass to NewRec.
1087     if (AddSubClass(NewRec, SCRef))
1088       return 0;
1089     NewRec->resolveReferences();
1090     Records.addDef(NewRec);
1091     
1092     // The result of the expression is a reference to the new record.
1093     return new DefInit(NewRec);
1094   }    
1095   case tgtok::l_brace: {           // Value ::= '{' ValueList '}'
1096     TGLoc BraceLoc = Lex.getLoc();
1097     Lex.Lex(); // eat the '{'
1098     std::vector<Init*> Vals;
1099     
1100     if (Lex.getCode() != tgtok::r_brace) {
1101       Vals = ParseValueList(CurRec);
1102       if (Vals.empty()) return 0;
1103     }
1104     if (Lex.getCode() != tgtok::r_brace) {
1105       TokError("expected '}' at end of bit list value");
1106       return 0;
1107     }
1108     Lex.Lex();  // eat the '}'
1109     
1110     BitsInit *Result = new BitsInit(Vals.size());
1111     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1112       Init *Bit = Vals[i]->convertInitializerTo(new BitRecTy());
1113       if (Bit == 0) {
1114         Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1115               ") is not convertable to a bit");
1116         return 0;
1117       }
1118       Result->setBit(Vals.size()-i-1, Bit);
1119     }
1120     return Result;
1121   }
1122   case tgtok::l_square: {          // Value ::= '[' ValueList ']'
1123     Lex.Lex(); // eat the '['
1124     std::vector<Init*> Vals;
1125     
1126     RecTy *DeducedEltTy = 0;
1127     ListRecTy *GivenListTy = 0;
1128     
1129     if (ItemType != 0) {
1130       ListRecTy *ListType = dynamic_cast<ListRecTy*>(ItemType);
1131       if (ListType == 0) {
1132         std::stringstream s;
1133         s << "Type mismatch for list, expected list type, got " 
1134           << ItemType->getAsString();
1135         TokError(s.str());
1136       }
1137       GivenListTy = ListType;
1138     }    
1139
1140     if (Lex.getCode() != tgtok::r_square) {
1141       Vals = ParseValueList(CurRec, 0, GivenListTy ? GivenListTy->getElementType() : 0);
1142       if (Vals.empty()) return 0;
1143     }
1144     if (Lex.getCode() != tgtok::r_square) {
1145       TokError("expected ']' at end of list value");
1146       return 0;
1147     }
1148     Lex.Lex();  // eat the ']'
1149
1150     RecTy *GivenEltTy = 0;
1151     if (Lex.getCode() == tgtok::less) {
1152       // Optional list element type
1153       Lex.Lex();  // eat the '<'
1154
1155       GivenEltTy = ParseType();
1156       if (GivenEltTy == 0) {
1157         // Couldn't parse element type
1158         return 0;
1159       }
1160
1161       if (Lex.getCode() != tgtok::greater) {
1162         TokError("expected '>' at end of list element type");
1163         return 0;
1164       }
1165       Lex.Lex();  // eat the '>'
1166     }
1167
1168     // Check elements
1169     RecTy *EltTy = 0;
1170     for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1171          i != ie;
1172          ++i) {
1173       TypedInit *TArg = dynamic_cast<TypedInit*>(*i);
1174       if (TArg == 0) {
1175         TokError("Untyped list element");
1176         return 0;
1177       }
1178       if (EltTy != 0) {
1179         EltTy = resolveTypes(EltTy, TArg->getType());
1180         if (EltTy == 0) {
1181           TokError("Incompatible types in list elements");
1182           return 0;
1183         }
1184       }
1185       else {
1186         EltTy = TArg->getType();
1187       }
1188     }
1189
1190     if (GivenEltTy != 0) {
1191       if (EltTy != 0) {
1192         // Verify consistency
1193         if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1194           TokError("Incompatible types in list elements");
1195           return 0;
1196         }
1197       }
1198       EltTy = GivenEltTy;
1199     }
1200
1201     if (EltTy == 0) {
1202       if (ItemType == 0) {
1203         TokError("No type for list");
1204         return 0;
1205       }
1206       DeducedEltTy = GivenListTy->getElementType();
1207    }
1208     else {
1209       // Make sure the deduced type is compatible with the given type
1210       if (GivenListTy) {
1211         if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1212           TokError("Element type mismatch for list");
1213           return 0;
1214         }
1215       }
1216       DeducedEltTy = EltTy;
1217     }
1218     
1219     return new ListInit(Vals, DeducedEltTy);
1220   }
1221   case tgtok::l_paren: {         // Value ::= '(' IDValue DagArgList ')'
1222     Lex.Lex();   // eat the '('
1223     if (Lex.getCode() != tgtok::Id
1224         && Lex.getCode() != tgtok::XCast
1225         && Lex.getCode() != tgtok::XNameConcat) {
1226       TokError("expected identifier in dag init");
1227       return 0;
1228     }
1229     
1230     Init *Operator = 0;
1231     if (Lex.getCode() == tgtok::Id) {
1232       Operator = ParseIDValue(CurRec);
1233       if (Operator == 0) return 0;
1234     }
1235     else {
1236       Operator = ParseOperation(CurRec);
1237       if (Operator == 0) return 0;
1238     }
1239
1240     // If the operator name is present, parse it.
1241     std::string OperatorName;
1242     if (Lex.getCode() == tgtok::colon) {
1243       if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1244         TokError("expected variable name in dag operator");
1245         return 0;
1246       }
1247       OperatorName = Lex.getCurStrVal();
1248       Lex.Lex();  // eat the VarName.
1249     }
1250     
1251     std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1252     if (Lex.getCode() != tgtok::r_paren) {
1253       DagArgs = ParseDagArgList(CurRec);
1254       if (DagArgs.empty()) return 0;
1255     }
1256     
1257     if (Lex.getCode() != tgtok::r_paren) {
1258       TokError("expected ')' in dag init");
1259       return 0;
1260     }
1261     Lex.Lex();  // eat the ')'
1262     
1263     return new DagInit(Operator, OperatorName, DagArgs);
1264     break;
1265   }
1266  
1267   case tgtok::XCar:
1268   case tgtok::XCdr:
1269   case tgtok::XNull:
1270   case tgtok::XCast:  // Value ::= !unop '(' Value ')'
1271   case tgtok::XConcat:
1272   case tgtok::XSRA: 
1273   case tgtok::XSRL:
1274   case tgtok::XSHL:
1275   case tgtok::XStrConcat:
1276   case tgtok::XRegMatch:
1277   case tgtok::XNameConcat:  // Value ::= !binop '(' Value ',' Value ')'
1278   case tgtok::XIf:
1279   case tgtok::XForEach:
1280   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1281     return ParseOperation(CurRec);
1282     break;
1283   }
1284   }
1285   
1286   return R;
1287 }
1288
1289 /// ParseValue - Parse a tblgen value.  This returns null on error.
1290 ///
1291 ///   Value       ::= SimpleValue ValueSuffix*
1292 ///   ValueSuffix ::= '{' BitList '}'
1293 ///   ValueSuffix ::= '[' BitList ']'
1294 ///   ValueSuffix ::= '.' ID
1295 ///
1296 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType) {
1297   Init *Result = ParseSimpleValue(CurRec, ItemType);
1298   if (Result == 0) return 0;
1299   
1300   // Parse the suffixes now if present.
1301   while (1) {
1302     switch (Lex.getCode()) {
1303     default: return Result;
1304     case tgtok::l_brace: {
1305       TGLoc CurlyLoc = Lex.getLoc();
1306       Lex.Lex(); // eat the '{'
1307       std::vector<unsigned> Ranges = ParseRangeList();
1308       if (Ranges.empty()) return 0;
1309       
1310       // Reverse the bitlist.
1311       std::reverse(Ranges.begin(), Ranges.end());
1312       Result = Result->convertInitializerBitRange(Ranges);
1313       if (Result == 0) {
1314         Error(CurlyLoc, "Invalid bit range for value");
1315         return 0;
1316       }
1317       
1318       // Eat the '}'.
1319       if (Lex.getCode() != tgtok::r_brace) {
1320         TokError("expected '}' at end of bit range list");
1321         return 0;
1322       }
1323       Lex.Lex();
1324       break;
1325     }
1326     case tgtok::l_square: {
1327       TGLoc SquareLoc = Lex.getLoc();
1328       Lex.Lex(); // eat the '['
1329       std::vector<unsigned> Ranges = ParseRangeList();
1330       if (Ranges.empty()) return 0;
1331       
1332       Result = Result->convertInitListSlice(Ranges);
1333       if (Result == 0) {
1334         Error(SquareLoc, "Invalid range for list slice");
1335         return 0;
1336       }
1337       
1338       // Eat the ']'.
1339       if (Lex.getCode() != tgtok::r_square) {
1340         TokError("expected ']' at end of list slice");
1341         return 0;
1342       }
1343       Lex.Lex();
1344       break;
1345     }
1346     case tgtok::period:
1347       if (Lex.Lex() != tgtok::Id) {  // eat the .
1348         TokError("expected field identifier after '.'");
1349         return 0;
1350       }
1351       if (!Result->getFieldType(Lex.getCurStrVal())) {
1352         TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1353                  Result->getAsString() + "'");
1354         return 0;
1355       }
1356       Result = new FieldInit(Result, Lex.getCurStrVal());
1357       Lex.Lex();  // eat field name
1358       break;
1359     }
1360   }
1361 }
1362
1363 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1364 ///
1365 ///    ParseDagArgList ::= Value (':' VARNAME)?
1366 ///    ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1367 std::vector<std::pair<llvm::Init*, std::string> > 
1368 TGParser::ParseDagArgList(Record *CurRec) {
1369   std::vector<std::pair<llvm::Init*, std::string> > Result;
1370   
1371   while (1) {
1372     Init *Val = ParseValue(CurRec);
1373     if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1374     
1375     // If the variable name is present, add it.
1376     std::string VarName;
1377     if (Lex.getCode() == tgtok::colon) {
1378       if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1379         TokError("expected variable name in dag literal");
1380         return std::vector<std::pair<llvm::Init*, std::string> >();
1381       }
1382       VarName = Lex.getCurStrVal();
1383       Lex.Lex();  // eat the VarName.
1384     }
1385     
1386     Result.push_back(std::make_pair(Val, VarName));
1387     
1388     if (Lex.getCode() != tgtok::comma) break;
1389     Lex.Lex(); // eat the ','    
1390   }
1391   
1392   return Result;
1393 }
1394
1395
1396 /// ParseValueList - Parse a comma separated list of values, returning them as a
1397 /// vector.  Note that this always expects to be able to parse at least one
1398 /// value.  It returns an empty list if this is not possible.
1399 ///
1400 ///   ValueList ::= Value (',' Value)
1401 ///
1402 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec, RecTy *EltTy) {
1403   std::vector<Init*> Result;
1404   RecTy *ItemType = EltTy;
1405   int ArgN = 0;
1406   if (ArgsRec != 0 && EltTy == 0) {
1407     const std::vector<std::string> &TArgs = ArgsRec->getTemplateArgs();
1408     const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1409     assert(RV && "Template argument record not found??");
1410     ItemType = RV->getType();
1411     ++ArgN;
1412   }
1413   Result.push_back(ParseValue(CurRec, ItemType));
1414   if (Result.back() == 0) return std::vector<Init*>();
1415   
1416   while (Lex.getCode() == tgtok::comma) {
1417     Lex.Lex();  // Eat the comma
1418     
1419     if (ArgsRec != 0 && EltTy == 0) {
1420       const std::vector<std::string> &TArgs = ArgsRec->getTemplateArgs();
1421       const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1422       assert(RV && "Template argument record not found??");
1423       ItemType = RV->getType();
1424       ++ArgN;
1425     }
1426     Result.push_back(ParseValue(CurRec, ItemType));
1427     if (Result.back() == 0) return std::vector<Init*>();
1428   }
1429   
1430   return Result;
1431 }
1432
1433
1434
1435 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1436 /// empty string on error.  This can happen in a number of different context's,
1437 /// including within a def or in the template args for a def (which which case
1438 /// CurRec will be non-null) and within the template args for a multiclass (in
1439 /// which case CurRec will be null, but CurMultiClass will be set).  This can
1440 /// also happen within a def that is within a multiclass, which will set both
1441 /// CurRec and CurMultiClass.
1442 ///
1443 ///  Declaration ::= FIELD? Type ID ('=' Value)?
1444 ///
1445 std::string TGParser::ParseDeclaration(Record *CurRec, 
1446                                        bool ParsingTemplateArgs) {
1447   // Read the field prefix if present.
1448   bool HasField = Lex.getCode() == tgtok::Field;
1449   if (HasField) Lex.Lex();
1450   
1451   RecTy *Type = ParseType();
1452   if (Type == 0) return "";
1453   
1454   if (Lex.getCode() != tgtok::Id) {
1455     TokError("Expected identifier in declaration");
1456     return "";
1457   }
1458   
1459   TGLoc IdLoc = Lex.getLoc();
1460   std::string DeclName = Lex.getCurStrVal();
1461   Lex.Lex();
1462   
1463   if (ParsingTemplateArgs) {
1464     if (CurRec) {
1465       DeclName = CurRec->getName() + ":" + DeclName;
1466     } else {
1467       assert(CurMultiClass);
1468     }
1469     if (CurMultiClass)
1470       DeclName = CurMultiClass->Rec.getName() + "::" + DeclName;
1471   }
1472   
1473   // Add the value.
1474   if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1475     return "";
1476   
1477   // If a value is present, parse it.
1478   if (Lex.getCode() == tgtok::equal) {
1479     Lex.Lex();
1480     TGLoc ValLoc = Lex.getLoc();
1481     Init *Val = ParseValue(CurRec, Type);
1482     if (Val == 0 ||
1483         SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1484       return "";
1485   }
1486   
1487   return DeclName;
1488 }
1489
1490 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1491 /// sequence of template-declarations in <>'s.  If CurRec is non-null, these are
1492 /// template args for a def, which may or may not be in a multiclass.  If null,
1493 /// these are the template args for a multiclass.
1494 ///
1495 ///    TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1496 /// 
1497 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1498   assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1499   Lex.Lex(); // eat the '<'
1500   
1501   Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1502   
1503   // Read the first declaration.
1504   std::string TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1505   if (TemplArg.empty())
1506     return true;
1507   
1508   TheRecToAddTo->addTemplateArg(TemplArg);
1509   
1510   while (Lex.getCode() == tgtok::comma) {
1511     Lex.Lex(); // eat the ','
1512     
1513     // Read the following declarations.
1514     TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1515     if (TemplArg.empty())
1516       return true;
1517     TheRecToAddTo->addTemplateArg(TemplArg);
1518   }
1519   
1520   if (Lex.getCode() != tgtok::greater)
1521     return TokError("expected '>' at end of template argument list");
1522   Lex.Lex(); // eat the '>'.
1523   return false;
1524 }
1525
1526
1527 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1528 ///
1529 ///   BodyItem ::= Declaration ';'
1530 ///   BodyItem ::= LET ID OptionalBitList '=' Value ';'
1531 bool TGParser::ParseBodyItem(Record *CurRec) {
1532   if (Lex.getCode() != tgtok::Let) {
1533     if (ParseDeclaration(CurRec, false).empty()) 
1534       return true;
1535     
1536     if (Lex.getCode() != tgtok::semi)
1537       return TokError("expected ';' after declaration");
1538     Lex.Lex();
1539     return false;
1540   }
1541
1542   // LET ID OptionalRangeList '=' Value ';'
1543   if (Lex.Lex() != tgtok::Id)
1544     return TokError("expected field identifier after let");
1545   
1546   TGLoc IdLoc = Lex.getLoc();
1547   std::string FieldName = Lex.getCurStrVal();
1548   Lex.Lex();  // eat the field name.
1549   
1550   std::vector<unsigned> BitList;
1551   if (ParseOptionalBitList(BitList)) 
1552     return true;
1553   std::reverse(BitList.begin(), BitList.end());
1554   
1555   if (Lex.getCode() != tgtok::equal)
1556     return TokError("expected '=' in let expression");
1557   Lex.Lex();  // eat the '='.
1558   
1559   RecordVal *Field = CurRec->getValue(FieldName);
1560   if (Field == 0)
1561     return TokError("Value '" + FieldName + "' unknown!");
1562
1563   RecTy *Type = Field->getType();
1564   
1565   Init *Val = ParseValue(CurRec, Type);
1566   if (Val == 0) return true;
1567   
1568   if (Lex.getCode() != tgtok::semi)
1569     return TokError("expected ';' after let expression");
1570   Lex.Lex();
1571   
1572   return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1573 }
1574
1575 /// ParseBody - Read the body of a class or def.  Return true on error, false on
1576 /// success.
1577 ///
1578 ///   Body     ::= ';'
1579 ///   Body     ::= '{' BodyList '}'
1580 ///   BodyList BodyItem*
1581 ///
1582 bool TGParser::ParseBody(Record *CurRec) {
1583   // If this is a null definition, just eat the semi and return.
1584   if (Lex.getCode() == tgtok::semi) {
1585     Lex.Lex();
1586     return false;
1587   }
1588   
1589   if (Lex.getCode() != tgtok::l_brace)
1590     return TokError("Expected ';' or '{' to start body");
1591   // Eat the '{'.
1592   Lex.Lex();
1593   
1594   while (Lex.getCode() != tgtok::r_brace)
1595     if (ParseBodyItem(CurRec))
1596       return true;
1597
1598   // Eat the '}'.
1599   Lex.Lex();
1600   return false;
1601 }
1602
1603 /// ParseObjectBody - Parse the body of a def or class.  This consists of an
1604 /// optional ClassList followed by a Body.  CurRec is the current def or class
1605 /// that is being parsed.
1606 ///
1607 ///   ObjectBody      ::= BaseClassList Body
1608 ///   BaseClassList   ::= /*empty*/
1609 ///   BaseClassList   ::= ':' BaseClassListNE
1610 ///   BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1611 ///
1612 bool TGParser::ParseObjectBody(Record *CurRec) {
1613   // If there is a baseclass list, read it.
1614   if (Lex.getCode() == tgtok::colon) {
1615     Lex.Lex();
1616     
1617     // Read all of the subclasses.
1618     SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1619     while (1) {
1620       // Check for error.
1621       if (SubClass.Rec == 0) return true;
1622      
1623       // Add it.
1624       if (AddSubClass(CurRec, SubClass))
1625         return true;
1626       
1627       if (Lex.getCode() != tgtok::comma) break;
1628       Lex.Lex(); // eat ','.
1629       SubClass = ParseSubClassReference(CurRec, false);
1630     }
1631   }
1632
1633   // Process any variables on the let stack.
1634   for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1635     for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1636       if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1637                    LetStack[i][j].Bits, LetStack[i][j].Value))
1638         return true;
1639   
1640   return ParseBody(CurRec);
1641 }
1642
1643
1644 /// ParseDef - Parse and return a top level or multiclass def, return the record
1645 /// corresponding to it.  This returns null on error.
1646 ///
1647 ///   DefInst ::= DEF ObjectName ObjectBody
1648 ///
1649 llvm::Record *TGParser::ParseDef(MultiClass *CurMultiClass) {
1650   TGLoc DefLoc = Lex.getLoc();
1651   assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1652   Lex.Lex();  // Eat the 'def' token.  
1653
1654   // Parse ObjectName and make a record for it.
1655   Record *CurRec = new Record(ParseObjectName(), DefLoc);
1656   
1657   if (!CurMultiClass) {
1658     // Top-level def definition.
1659     
1660     // Ensure redefinition doesn't happen.
1661     if (Records.getDef(CurRec->getName())) {
1662       Error(DefLoc, "def '" + CurRec->getName() + "' already defined");
1663       return 0;
1664     }
1665     Records.addDef(CurRec);
1666   } else {
1667     // Otherwise, a def inside a multiclass, add it to the multiclass.
1668     for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1669       if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
1670         Error(DefLoc, "def '" + CurRec->getName() +
1671               "' already defined in this multiclass!");
1672         return 0;
1673       }
1674     CurMultiClass->DefPrototypes.push_back(CurRec);
1675   }
1676   
1677   if (ParseObjectBody(CurRec))
1678     return 0;
1679   
1680   if (CurMultiClass == 0)  // Def's in multiclasses aren't really defs.
1681     CurRec->resolveReferences();
1682   
1683   // If ObjectBody has template arguments, it's an error.
1684   assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1685   return CurRec;
1686 }
1687
1688
1689 /// ParseClass - Parse a tblgen class definition.
1690 ///
1691 ///   ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1692 ///
1693 bool TGParser::ParseClass() {
1694   assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1695   Lex.Lex();
1696   
1697   if (Lex.getCode() != tgtok::Id)
1698     return TokError("expected class name after 'class' keyword");
1699   
1700   Record *CurRec = Records.getClass(Lex.getCurStrVal());
1701   if (CurRec) {
1702     // If the body was previously defined, this is an error.
1703     if (!CurRec->getValues().empty() ||
1704         !CurRec->getSuperClasses().empty() ||
1705         !CurRec->getTemplateArgs().empty())
1706       return TokError("Class '" + CurRec->getName() + "' already defined");
1707   } else {
1708     // If this is the first reference to this class, create and add it.
1709     CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc());
1710     Records.addClass(CurRec);
1711   }
1712   Lex.Lex(); // eat the name.
1713   
1714   // If there are template args, parse them.
1715   if (Lex.getCode() == tgtok::less)
1716     if (ParseTemplateArgList(CurRec))
1717       return true;
1718
1719   // Finally, parse the object body.
1720   return ParseObjectBody(CurRec);
1721 }
1722
1723 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1724 /// of LetRecords.
1725 ///
1726 ///   LetList ::= LetItem (',' LetItem)*
1727 ///   LetItem ::= ID OptionalRangeList '=' Value
1728 ///
1729 std::vector<LetRecord> TGParser::ParseLetList() {
1730   std::vector<LetRecord> Result;
1731   
1732   while (1) {
1733     if (Lex.getCode() != tgtok::Id) {
1734       TokError("expected identifier in let definition");
1735       return std::vector<LetRecord>();
1736     }
1737     std::string Name = Lex.getCurStrVal();
1738     TGLoc NameLoc = Lex.getLoc();
1739     Lex.Lex();  // Eat the identifier. 
1740
1741     // Check for an optional RangeList.
1742     std::vector<unsigned> Bits;
1743     if (ParseOptionalRangeList(Bits)) 
1744       return std::vector<LetRecord>();
1745     std::reverse(Bits.begin(), Bits.end());
1746     
1747     if (Lex.getCode() != tgtok::equal) {
1748       TokError("expected '=' in let expression");
1749       return std::vector<LetRecord>();
1750     }
1751     Lex.Lex();  // eat the '='.
1752     
1753     Init *Val = ParseValue(0);
1754     if (Val == 0) return std::vector<LetRecord>();
1755     
1756     // Now that we have everything, add the record.
1757     Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1758     
1759     if (Lex.getCode() != tgtok::comma)
1760       return Result;
1761     Lex.Lex();  // eat the comma.    
1762   }
1763 }
1764
1765 /// ParseTopLevelLet - Parse a 'let' at top level.  This can be a couple of
1766 /// different related productions.
1767 ///
1768 ///   Object ::= LET LetList IN '{' ObjectList '}'
1769 ///   Object ::= LET LetList IN Object
1770 ///
1771 bool TGParser::ParseTopLevelLet() {
1772   assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1773   Lex.Lex();
1774   
1775   // Add this entry to the let stack.
1776   std::vector<LetRecord> LetInfo = ParseLetList();
1777   if (LetInfo.empty()) return true;
1778   LetStack.push_back(LetInfo);
1779
1780   if (Lex.getCode() != tgtok::In)
1781     return TokError("expected 'in' at end of top-level 'let'");
1782   Lex.Lex();
1783   
1784   // If this is a scalar let, just handle it now
1785   if (Lex.getCode() != tgtok::l_brace) {
1786     // LET LetList IN Object
1787     if (ParseObject())
1788       return true;
1789   } else {   // Object ::= LETCommand '{' ObjectList '}'
1790     TGLoc BraceLoc = Lex.getLoc();
1791     // Otherwise, this is a group let.
1792     Lex.Lex();  // eat the '{'.
1793     
1794     // Parse the object list.
1795     if (ParseObjectList())
1796       return true;
1797     
1798     if (Lex.getCode() != tgtok::r_brace) {
1799       TokError("expected '}' at end of top level let command");
1800       return Error(BraceLoc, "to match this '{'");
1801     }
1802     Lex.Lex();
1803   }
1804   
1805   // Outside this let scope, this let block is not active.
1806   LetStack.pop_back();
1807   return false;
1808 }
1809
1810 /// ParseMultiClassDef - Parse a def in a multiclass context.
1811 ///
1812 ///  MultiClassDef ::= DefInst
1813 ///
1814 bool TGParser::ParseMultiClassDef(MultiClass *CurMC) {
1815   if (Lex.getCode() != tgtok::Def) 
1816     return TokError("expected 'def' in multiclass body");
1817
1818   Record *D = ParseDef(CurMC);
1819   if (D == 0) return true;
1820   
1821   // Copy the template arguments for the multiclass into the def.
1822   const std::vector<std::string> &TArgs = CurMC->Rec.getTemplateArgs();
1823   
1824   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1825     const RecordVal *RV = CurMC->Rec.getValue(TArgs[i]);
1826     assert(RV && "Template arg doesn't exist?");
1827     D->addValue(*RV);
1828   }
1829
1830   return false;
1831 }
1832
1833 /// ParseMultiClass - Parse a multiclass definition.
1834 ///
1835 ///  MultiClassInst ::= MULTICLASS ID TemplateArgList?
1836 ///                     ':' BaseMultiClassList '{' MultiClassDef+ '}'
1837 ///
1838 bool TGParser::ParseMultiClass() {
1839   assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1840   Lex.Lex();  // Eat the multiclass token.
1841
1842   if (Lex.getCode() != tgtok::Id)
1843     return TokError("expected identifier after multiclass for name");
1844   std::string Name = Lex.getCurStrVal();
1845   
1846   if (MultiClasses.count(Name))
1847     return TokError("multiclass '" + Name + "' already defined");
1848   
1849   CurMultiClass = MultiClasses[Name] = new MultiClass(Name, Lex.getLoc());
1850   Lex.Lex();  // Eat the identifier.
1851   
1852   // If there are template args, parse them.
1853   if (Lex.getCode() == tgtok::less)
1854     if (ParseTemplateArgList(0))
1855       return true;
1856
1857   bool inherits = false;
1858
1859   // If there are submulticlasses, parse them.
1860   if (Lex.getCode() == tgtok::colon) {
1861     inherits = true;
1862
1863     Lex.Lex();
1864
1865     // Read all of the submulticlasses.
1866     SubMultiClassReference SubMultiClass =
1867       ParseSubMultiClassReference(CurMultiClass);
1868     while (1) {
1869       // Check for error.
1870       if (SubMultiClass.MC == 0) return true;
1871
1872       // Add it.
1873       if (AddSubMultiClass(CurMultiClass, SubMultiClass))
1874         return true;
1875
1876       if (Lex.getCode() != tgtok::comma) break;
1877       Lex.Lex(); // eat ','.
1878       SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1879     }
1880   }
1881
1882   if (Lex.getCode() != tgtok::l_brace) {
1883     if (!inherits)
1884       return TokError("expected '{' in multiclass definition");
1885     else
1886       if (Lex.getCode() != tgtok::semi)
1887         return TokError("expected ';' in multiclass definition");
1888       else
1889         Lex.Lex();  // eat the ';'.
1890   }
1891   else {
1892     if (Lex.Lex() == tgtok::r_brace)  // eat the '{'.
1893       return TokError("multiclass must contain at least one def");
1894   
1895     while (Lex.getCode() != tgtok::r_brace)
1896       if (ParseMultiClassDef(CurMultiClass))
1897         return true;
1898   
1899     Lex.Lex();  // eat the '}'.
1900   }
1901   
1902   CurMultiClass = 0;
1903   return false;
1904 }
1905
1906 /// ParseDefm - Parse the instantiation of a multiclass.
1907 ///
1908 ///   DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
1909 ///
1910 bool TGParser::ParseDefm() {
1911   assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
1912   if (Lex.Lex() != tgtok::Id)  // eat the defm.
1913     return TokError("expected identifier after defm");
1914   
1915   TGLoc DefmPrefixLoc = Lex.getLoc();
1916   std::string DefmPrefix = Lex.getCurStrVal();
1917   if (Lex.Lex() != tgtok::colon)
1918     return TokError("expected ':' after defm identifier");
1919   
1920   // eat the colon.
1921   Lex.Lex();
1922
1923   TGLoc SubClassLoc = Lex.getLoc();
1924   SubClassReference Ref = ParseSubClassReference(0, true);
1925
1926   while (1) {
1927     if (Ref.Rec == 0) return true;
1928
1929     // To instantiate a multiclass, we need to first get the multiclass, then
1930     // instantiate each def contained in the multiclass with the SubClassRef
1931     // template parameters.
1932     MultiClass *MC = MultiClasses[Ref.Rec->getName()];
1933     assert(MC && "Didn't lookup multiclass correctly?");
1934     std::vector<Init*> &TemplateVals = Ref.TemplateArgs;   
1935
1936     // Verify that the correct number of template arguments were specified.
1937     const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
1938     if (TArgs.size() < TemplateVals.size())
1939       return Error(SubClassLoc,
1940                    "more template args specified than multiclass expects");
1941
1942     // Loop over all the def's in the multiclass, instantiating each one.
1943     for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
1944       Record *DefProto = MC->DefPrototypes[i];
1945
1946       // Add in the defm name
1947       std::string DefName = DefProto->getName();
1948       std::string::size_type idx = DefName.find("#NAME#");
1949       if (idx != std::string::npos) {
1950         DefName.replace(idx, 6, DefmPrefix);
1951       }
1952       else {
1953         // Add the suffix to the defm name to get the new name.
1954         DefName = DefmPrefix + DefName;
1955       }
1956
1957       Record *CurRec = new Record(DefName, DefmPrefixLoc);
1958
1959       SubClassReference Ref;
1960       Ref.RefLoc = DefmPrefixLoc;
1961       Ref.Rec = DefProto;
1962       AddSubClass(CurRec, Ref);
1963
1964       // Loop over all of the template arguments, setting them to the specified
1965       // value or leaving them as the default if necessary.
1966       for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1967         // Check if a value is specified for this temp-arg.
1968         if (i < TemplateVals.size()) {
1969           // Set it now.
1970           if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1971                        TemplateVals[i]))
1972             return true;
1973
1974           // Resolve it next.
1975           CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1976
1977           // Now remove it.
1978           CurRec->removeValue(TArgs[i]);
1979
1980         } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
1981           return Error(SubClassLoc,
1982                        "value not specified for template argument #"+
1983                        utostr(i) + " (" + TArgs[i] + ") of multiclassclass '" +
1984                        MC->Rec.getName() + "'");
1985         }
1986       }
1987
1988       // If the mdef is inside a 'let' expression, add to each def.
1989       for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1990         for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1991           if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1992                        LetStack[i][j].Bits, LetStack[i][j].Value)) {
1993             Error(DefmPrefixLoc, "when instantiating this defm");
1994             return true;
1995           }
1996
1997       // Ensure redefinition doesn't happen.
1998       if (Records.getDef(CurRec->getName()))
1999         return Error(DefmPrefixLoc, "def '" + CurRec->getName() + 
2000                      "' already defined, instantiating defm with subdef '" + 
2001                      DefProto->getName() + "'");
2002       Records.addDef(CurRec);
2003       CurRec->resolveReferences();
2004     }
2005
2006     if (Lex.getCode() != tgtok::comma) break;
2007     Lex.Lex(); // eat ','.
2008
2009     SubClassLoc = Lex.getLoc();
2010     Ref = ParseSubClassReference(0, true);
2011   }
2012
2013   if (Lex.getCode() != tgtok::semi)
2014     return TokError("expected ';' at end of defm");
2015   Lex.Lex();
2016   
2017   return false;
2018 }
2019
2020 /// ParseObject
2021 ///   Object ::= ClassInst
2022 ///   Object ::= DefInst
2023 ///   Object ::= MultiClassInst
2024 ///   Object ::= DefMInst
2025 ///   Object ::= LETCommand '{' ObjectList '}'
2026 ///   Object ::= LETCommand Object
2027 bool TGParser::ParseObject() {
2028   switch (Lex.getCode()) {
2029   default: assert(0 && "This is not an object");
2030   case tgtok::Let:   return ParseTopLevelLet();
2031   case tgtok::Def:   return ParseDef(0) == 0;
2032   case tgtok::Defm:  return ParseDefm();
2033   case tgtok::Class: return ParseClass();
2034   case tgtok::MultiClass: return ParseMultiClass();
2035   }
2036 }
2037
2038 /// ParseObjectList
2039 ///   ObjectList :== Object*
2040 bool TGParser::ParseObjectList() {
2041   while (isObjectStart(Lex.getCode())) {
2042     if (ParseObject())
2043       return true;
2044   }
2045   return false;
2046 }
2047
2048
2049 bool TGParser::ParseFile() {
2050   Lex.Lex(); // Prime the lexer.
2051   if (ParseObjectList()) return true;
2052   
2053   // If we have unread input at the end of the file, report it.
2054   if (Lex.getCode() == tgtok::Eof)
2055     return false;
2056   
2057   return TokError("Unexpected input at top level");
2058 }
2059