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