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