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