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