1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Implement the Parser for TableGen.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TGParser.h"
14 #include "llvm/ADT/None.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Config/llvm-config.h"
20 #include "llvm/Support/Casting.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include <algorithm>
26 #include <cassert>
27 #include <cstdint>
28 
29 using namespace llvm;
30 
31 //===----------------------------------------------------------------------===//
32 // Support Code for the Semantic Actions.
33 //===----------------------------------------------------------------------===//
34 
35 namespace llvm {
36 
37 struct SubClassReference {
38   SMRange RefRange;
39   Record *Rec;
40   SmallVector<Init*, 4> TemplateArgs;
41 
42   SubClassReference() : Rec(nullptr) {}
43 
44   bool isInvalid() const { return Rec == nullptr; }
45 };
46 
47 struct SubMultiClassReference {
48   SMRange RefRange;
49   MultiClass *MC;
50   SmallVector<Init*, 4> TemplateArgs;
51 
52   SubMultiClassReference() : MC(nullptr) {}
53 
54   bool isInvalid() const { return MC == nullptr; }
55   void dump() const;
56 };
57 
58 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
59 LLVM_DUMP_METHOD void SubMultiClassReference::dump() const {
60   errs() << "Multiclass:\n";
61 
62   MC->dump();
63 
64   errs() << "Template args:\n";
65   for (Init *TA : TemplateArgs)
66     TA->dump();
67 }
68 #endif
69 
70 } // end namespace llvm
71 
72 static bool checkBitsConcrete(Record &R, const RecordVal &RV) {
73   BitsInit *BV = cast<BitsInit>(RV.getValue());
74   for (unsigned i = 0, e = BV->getNumBits(); i != e; ++i) {
75     Init *Bit = BV->getBit(i);
76     bool IsReference = false;
77     if (auto VBI = dyn_cast<VarBitInit>(Bit)) {
78       if (auto VI = dyn_cast<VarInit>(VBI->getBitVar())) {
79         if (R.getValue(VI->getName()))
80           IsReference = true;
81       }
82     } else if (isa<VarInit>(Bit)) {
83       IsReference = true;
84     }
85     if (!(IsReference || Bit->isConcrete()))
86       return false;
87   }
88   return true;
89 }
90 
91 static void checkConcrete(Record &R) {
92   for (const RecordVal &RV : R.getValues()) {
93     // HACK: Disable this check for variables declared with 'field'. This is
94     // done merely because existing targets have legitimate cases of
95     // non-concrete variables in helper defs. Ideally, we'd introduce a
96     // 'maybe' or 'optional' modifier instead of this.
97     if (RV.getPrefix())
98       continue;
99 
100     if (Init *V = RV.getValue()) {
101       bool Ok = isa<BitsInit>(V) ? checkBitsConcrete(R, RV) : V->isConcrete();
102       if (!Ok) {
103         PrintError(R.getLoc(),
104                    Twine("Initializer of '") + RV.getNameInitAsString() +
105                    "' in '" + R.getNameInitAsString() +
106                    "' could not be fully resolved: " +
107                    RV.getValue()->getAsString());
108       }
109     }
110   }
111 }
112 
113 /// Return an Init with a qualifier prefix referring
114 /// to CurRec's name.
115 static Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
116                         Init *Name, StringRef Scoper) {
117   Init *NewName =
118       BinOpInit::getStrConcat(CurRec.getNameInit(), StringInit::get(Scoper));
119   NewName = BinOpInit::getStrConcat(NewName, Name);
120   if (CurMultiClass && Scoper != "::") {
121     Init *Prefix = BinOpInit::getStrConcat(CurMultiClass->Rec.getNameInit(),
122                                            StringInit::get("::"));
123     NewName = BinOpInit::getStrConcat(Prefix, NewName);
124   }
125 
126   if (BinOpInit *BinOp = dyn_cast<BinOpInit>(NewName))
127     NewName = BinOp->Fold(&CurRec);
128   return NewName;
129 }
130 
131 /// Return the qualified version of the implicit 'NAME' template argument.
132 static Init *QualifiedNameOfImplicitName(Record &Rec,
133                                          MultiClass *MC = nullptr) {
134   return QualifyName(Rec, MC, StringInit::get("NAME"), MC ? "::" : ":");
135 }
136 
137 static Init *QualifiedNameOfImplicitName(MultiClass *MC) {
138   return QualifiedNameOfImplicitName(MC->Rec, MC);
139 }
140 
141 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
142   if (!CurRec)
143     CurRec = &CurMultiClass->Rec;
144 
145   if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
146     // The value already exists in the class, treat this as a set.
147     if (ERV->setValue(RV.getValue()))
148       return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
149                    RV.getType()->getAsString() + "' is incompatible with " +
150                    "previous definition of type '" +
151                    ERV->getType()->getAsString() + "'");
152   } else {
153     CurRec->addValue(RV);
154   }
155   return false;
156 }
157 
158 /// SetValue -
159 /// Return true on error, false on success.
160 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
161                         ArrayRef<unsigned> BitList, Init *V,
162                         bool AllowSelfAssignment) {
163   if (!V) return false;
164 
165   if (!CurRec) CurRec = &CurMultiClass->Rec;
166 
167   RecordVal *RV = CurRec->getValue(ValName);
168   if (!RV)
169     return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
170                  "' unknown!");
171 
172   // Do not allow assignments like 'X = X'.  This will just cause infinite loops
173   // in the resolution machinery.
174   if (BitList.empty())
175     if (VarInit *VI = dyn_cast<VarInit>(V))
176       if (VI->getNameInit() == ValName && !AllowSelfAssignment)
177         return Error(Loc, "Recursion / self-assignment forbidden");
178 
179   // If we are assigning to a subset of the bits in the value... then we must be
180   // assigning to a field of BitsRecTy, which must have a BitsInit
181   // initializer.
182   //
183   if (!BitList.empty()) {
184     BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
185     if (!CurVal)
186       return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
187                    "' is not a bits type");
188 
189     // Convert the incoming value to a bits type of the appropriate size...
190     Init *BI = V->getCastTo(BitsRecTy::get(BitList.size()));
191     if (!BI)
192       return Error(Loc, "Initializer is not compatible with bit range");
193 
194     SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
195 
196     // Loop over bits, assigning values as appropriate.
197     for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
198       unsigned Bit = BitList[i];
199       if (NewBits[Bit])
200         return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
201                      ValName->getAsUnquotedString() + "' more than once");
202       NewBits[Bit] = BI->getBit(i);
203     }
204 
205     for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
206       if (!NewBits[i])
207         NewBits[i] = CurVal->getBit(i);
208 
209     V = BitsInit::get(NewBits);
210   }
211 
212   if (RV->setValue(V, Loc)) {
213     std::string InitType;
214     if (BitsInit *BI = dyn_cast<BitsInit>(V))
215       InitType = (Twine("' of type bit initializer with length ") +
216                   Twine(BI->getNumBits())).str();
217     else if (TypedInit *TI = dyn_cast<TypedInit>(V))
218       InitType = (Twine("' of type '") + TI->getType()->getAsString()).str();
219     return Error(Loc, "Field '" + ValName->getAsUnquotedString() +
220                           "' of type '" + RV->getType()->getAsString() +
221                           "' is incompatible with value '" +
222                           V->getAsString() + InitType + "'");
223   }
224   return false;
225 }
226 
227 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
228 /// args as SubClass's template arguments.
229 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
230   Record *SC = SubClass.Rec;
231   // Add all of the values in the subclass into the current class.
232   for (const RecordVal &Val : SC->getValues())
233     if (AddValue(CurRec, SubClass.RefRange.Start, Val))
234       return true;
235 
236   ArrayRef<Init *> TArgs = SC->getTemplateArgs();
237 
238   // Ensure that an appropriate number of template arguments are specified.
239   if (TArgs.size() < SubClass.TemplateArgs.size())
240     return Error(SubClass.RefRange.Start,
241                  "More template args specified than expected");
242 
243   // Loop over all of the template arguments, setting them to the specified
244   // value or leaving them as the default if necessary.
245   MapResolver R(CurRec);
246 
247   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
248     if (i < SubClass.TemplateArgs.size()) {
249       // If a value is specified for this template arg, set it now.
250       if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
251                    None, SubClass.TemplateArgs[i]))
252         return true;
253     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
254       return Error(SubClass.RefRange.Start,
255                    "Value not specified for template argument #" +
256                    Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
257                    ") of subclass '" + SC->getNameInitAsString() + "'!");
258     }
259 
260     R.set(TArgs[i], CurRec->getValue(TArgs[i])->getValue());
261 
262     CurRec->removeValue(TArgs[i]);
263   }
264 
265   Init *Name;
266   if (CurRec->isClass())
267     Name =
268         VarInit::get(QualifiedNameOfImplicitName(*CurRec), StringRecTy::get());
269   else
270     Name = CurRec->getNameInit();
271   R.set(QualifiedNameOfImplicitName(*SC), Name);
272 
273   CurRec->resolveReferences(R);
274 
275   // Since everything went well, we can now set the "superclass" list for the
276   // current record.
277   ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses();
278   for (const auto &SCPair : SCs) {
279     if (CurRec->isSubClassOf(SCPair.first))
280       return Error(SubClass.RefRange.Start,
281                    "Already subclass of '" + SCPair.first->getName() + "'!\n");
282     CurRec->addSuperClass(SCPair.first, SCPair.second);
283   }
284 
285   if (CurRec->isSubClassOf(SC))
286     return Error(SubClass.RefRange.Start,
287                  "Already subclass of '" + SC->getName() + "'!\n");
288   CurRec->addSuperClass(SC, SubClass.RefRange);
289   return false;
290 }
291 
292 bool TGParser::AddSubClass(RecordsEntry &Entry, SubClassReference &SubClass) {
293   if (Entry.Rec)
294     return AddSubClass(Entry.Rec.get(), SubClass);
295 
296   for (auto &E : Entry.Loop->Entries) {
297     if (AddSubClass(E, SubClass))
298       return true;
299   }
300 
301   return false;
302 }
303 
304 /// AddSubMultiClass - Add SubMultiClass as a subclass to
305 /// CurMC, resolving its template args as SubMultiClass's
306 /// template arguments.
307 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
308                                 SubMultiClassReference &SubMultiClass) {
309   MultiClass *SMC = SubMultiClass.MC;
310 
311   ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs();
312   if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
313     return Error(SubMultiClass.RefRange.Start,
314                  "More template args specified than expected");
315 
316   // Prepare the mapping of template argument name to value, filling in default
317   // values if necessary.
318   SubstStack TemplateArgs;
319   for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
320     if (i < SubMultiClass.TemplateArgs.size()) {
321       TemplateArgs.emplace_back(SMCTArgs[i], SubMultiClass.TemplateArgs[i]);
322     } else {
323       Init *Default = SMC->Rec.getValue(SMCTArgs[i])->getValue();
324       if (!Default->isComplete()) {
325         return Error(SubMultiClass.RefRange.Start,
326                      "value not specified for template argument #" + Twine(i) +
327                          " (" + SMCTArgs[i]->getAsUnquotedString() +
328                          ") of multiclass '" + SMC->Rec.getNameInitAsString() +
329                          "'");
330       }
331       TemplateArgs.emplace_back(SMCTArgs[i], Default);
332     }
333   }
334 
335   TemplateArgs.emplace_back(
336       QualifiedNameOfImplicitName(SMC),
337       VarInit::get(QualifiedNameOfImplicitName(CurMC), StringRecTy::get()));
338 
339   // Add all of the defs in the subclass into the current multiclass.
340   return resolve(SMC->Entries, TemplateArgs, false, &CurMC->Entries);
341 }
342 
343 /// Add a record or foreach loop to the current context (global record keeper,
344 /// current inner-most foreach loop, or multiclass).
345 bool TGParser::addEntry(RecordsEntry E) {
346   assert(!E.Rec || !E.Loop);
347 
348   if (!Loops.empty()) {
349     Loops.back()->Entries.push_back(std::move(E));
350     return false;
351   }
352 
353   if (E.Loop) {
354     SubstStack Stack;
355     return resolve(*E.Loop, Stack, CurMultiClass == nullptr,
356                    CurMultiClass ? &CurMultiClass->Entries : nullptr);
357   }
358 
359   if (CurMultiClass) {
360     CurMultiClass->Entries.push_back(std::move(E));
361     return false;
362   }
363 
364   return addDefOne(std::move(E.Rec));
365 }
366 
367 /// Resolve the entries in \p Loop, going over inner loops recursively
368 /// and making the given subsitutions of (name, value) pairs.
369 ///
370 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
371 /// are added to the global record keeper.
372 bool TGParser::resolve(const ForeachLoop &Loop, SubstStack &Substs,
373                        bool Final, std::vector<RecordsEntry> *Dest,
374                        SMLoc *Loc) {
375   MapResolver R;
376   for (const auto &S : Substs)
377     R.set(S.first, S.second);
378   Init *List = Loop.ListValue->resolveReferences(R);
379   auto LI = dyn_cast<ListInit>(List);
380   if (!LI) {
381     if (!Final) {
382       Dest->emplace_back(std::make_unique<ForeachLoop>(Loop.Loc, Loop.IterVar,
383                                                   List));
384       return resolve(Loop.Entries, Substs, Final, &Dest->back().Loop->Entries,
385                      Loc);
386     }
387 
388     PrintError(Loop.Loc, Twine("attempting to loop over '") +
389                               List->getAsString() + "', expected a list");
390     return true;
391   }
392 
393   bool Error = false;
394   for (auto Elt : *LI) {
395     if (Loop.IterVar)
396       Substs.emplace_back(Loop.IterVar->getNameInit(), Elt);
397     Error = resolve(Loop.Entries, Substs, Final, Dest);
398     if (Loop.IterVar)
399       Substs.pop_back();
400     if (Error)
401       break;
402   }
403   return Error;
404 }
405 
406 /// Resolve the entries in \p Source, going over loops recursively and
407 /// making the given substitutions of (name, value) pairs.
408 ///
409 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
410 /// are added to the global record keeper.
411 bool TGParser::resolve(const std::vector<RecordsEntry> &Source,
412                        SubstStack &Substs, bool Final,
413                        std::vector<RecordsEntry> *Dest, SMLoc *Loc) {
414   bool Error = false;
415   for (auto &E : Source) {
416     if (E.Loop) {
417       Error = resolve(*E.Loop, Substs, Final, Dest);
418     } else {
419       auto Rec = std::make_unique<Record>(*E.Rec);
420       if (Loc)
421         Rec->appendLoc(*Loc);
422 
423       MapResolver R(Rec.get());
424       for (const auto &S : Substs)
425         R.set(S.first, S.second);
426       Rec->resolveReferences(R);
427 
428       if (Dest)
429         Dest->push_back(std::move(Rec));
430       else
431         Error = addDefOne(std::move(Rec));
432     }
433     if (Error)
434       break;
435   }
436   return Error;
437 }
438 
439 /// Resolve the record fully and add it to the record keeper.
440 bool TGParser::addDefOne(std::unique_ptr<Record> Rec) {
441   if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) {
442     if (!Rec->isAnonymous()) {
443       PrintError(Rec->getLoc(),
444                  "def already exists: " + Rec->getNameInitAsString());
445       PrintNote(Prev->getLoc(), "location of previous definition");
446       return true;
447     }
448     Rec->setName(Records.getNewAnonymousName());
449   }
450 
451   Rec->resolveReferences();
452   checkConcrete(*Rec);
453 
454   if (!isa<StringInit>(Rec->getNameInit())) {
455     PrintError(Rec->getLoc(), Twine("record name '") +
456                                   Rec->getNameInit()->getAsString() +
457                                   "' could not be fully resolved");
458     return true;
459   }
460 
461   // If ObjectBody has template arguments, it's an error.
462   assert(Rec->getTemplateArgs().empty() && "How'd this get template args?");
463 
464   for (DefsetRecord *Defset : Defsets) {
465     DefInit *I = Rec->getDefInit();
466     if (!I->getType()->typeIsA(Defset->EltTy)) {
467       PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") +
468                                     I->getType()->getAsString() +
469                                      "' to defset");
470       PrintNote(Defset->Loc, "location of defset declaration");
471       return true;
472     }
473     Defset->Elements.push_back(I);
474   }
475 
476   Records.addDef(std::move(Rec));
477   return false;
478 }
479 
480 //===----------------------------------------------------------------------===//
481 // Parser Code
482 //===----------------------------------------------------------------------===//
483 
484 /// isObjectStart - Return true if this is a valid first token for an Object.
485 static bool isObjectStart(tgtok::TokKind K) {
486   return K == tgtok::Class || K == tgtok::Def || K == tgtok::Defm ||
487          K == tgtok::Let || K == tgtok::MultiClass || K == tgtok::Foreach ||
488          K == tgtok::Defset || K == tgtok::Defvar || K == tgtok::If;
489 }
490 
491 bool TGParser::consume(tgtok::TokKind K) {
492   if (Lex.getCode() == K) {
493     Lex.Lex();
494     return true;
495   }
496   return false;
497 }
498 
499 /// ParseObjectName - If a valid object name is specified, return it. If no
500 /// name is specified, return the unset initializer. Return nullptr on parse
501 /// error.
502 ///   ObjectName ::= Value [ '#' Value ]*
503 ///   ObjectName ::= /*empty*/
504 ///
505 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
506   switch (Lex.getCode()) {
507   case tgtok::colon:
508   case tgtok::semi:
509   case tgtok::l_brace:
510     // These are all of the tokens that can begin an object body.
511     // Some of these can also begin values but we disallow those cases
512     // because they are unlikely to be useful.
513     return UnsetInit::get();
514   default:
515     break;
516   }
517 
518   Record *CurRec = nullptr;
519   if (CurMultiClass)
520     CurRec = &CurMultiClass->Rec;
521 
522   Init *Name = ParseValue(CurRec, StringRecTy::get(), ParseNameMode);
523   if (!Name)
524     return nullptr;
525 
526   if (CurMultiClass) {
527     Init *NameStr = QualifiedNameOfImplicitName(CurMultiClass);
528     HasReferenceResolver R(NameStr);
529     Name->resolveReferences(R);
530     if (!R.found())
531       Name = BinOpInit::getStrConcat(VarInit::get(NameStr, StringRecTy::get()),
532                                      Name);
533   }
534 
535   return Name;
536 }
537 
538 /// ParseClassID - Parse and resolve a reference to a class name.  This returns
539 /// null on error.
540 ///
541 ///    ClassID ::= ID
542 ///
543 Record *TGParser::ParseClassID() {
544   if (Lex.getCode() != tgtok::Id) {
545     TokError("expected name for ClassID");
546     return nullptr;
547   }
548 
549   Record *Result = Records.getClass(Lex.getCurStrVal());
550   if (!Result) {
551     std::string Msg("Couldn't find class '" + Lex.getCurStrVal() + "'");
552     if (MultiClasses[Lex.getCurStrVal()].get())
553       TokError(Msg + ". Use 'defm' if you meant to use multiclass '" +
554                Lex.getCurStrVal() + "'");
555     else
556       TokError(Msg);
557   }
558 
559   Lex.Lex();
560   return Result;
561 }
562 
563 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
564 /// This returns null on error.
565 ///
566 ///    MultiClassID ::= ID
567 ///
568 MultiClass *TGParser::ParseMultiClassID() {
569   if (Lex.getCode() != tgtok::Id) {
570     TokError("expected name for MultiClassID");
571     return nullptr;
572   }
573 
574   MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
575   if (!Result)
576     TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
577 
578   Lex.Lex();
579   return Result;
580 }
581 
582 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
583 /// subclass.  This returns a SubClassRefTy with a null Record* on error.
584 ///
585 ///  SubClassRef ::= ClassID
586 ///  SubClassRef ::= ClassID '<' ValueList '>'
587 ///
588 SubClassReference TGParser::
589 ParseSubClassReference(Record *CurRec, bool isDefm) {
590   SubClassReference Result;
591   Result.RefRange.Start = Lex.getLoc();
592 
593   if (isDefm) {
594     if (MultiClass *MC = ParseMultiClassID())
595       Result.Rec = &MC->Rec;
596   } else {
597     Result.Rec = ParseClassID();
598   }
599   if (!Result.Rec) return Result;
600 
601   // If there is no template arg list, we're done.
602   if (!consume(tgtok::less)) {
603     Result.RefRange.End = Lex.getLoc();
604     return Result;
605   }
606 
607   if (Lex.getCode() == tgtok::greater) {
608     TokError("subclass reference requires a non-empty list of template values");
609     Result.Rec = nullptr;
610     return Result;
611   }
612 
613   ParseValueList(Result.TemplateArgs, CurRec, Result.Rec);
614   if (Result.TemplateArgs.empty()) {
615     Result.Rec = nullptr;   // Error parsing value list.
616     return Result;
617   }
618 
619   if (!consume(tgtok::greater)) {
620     TokError("expected '>' in template value list");
621     Result.Rec = nullptr;
622     return Result;
623   }
624   Result.RefRange.End = Lex.getLoc();
625 
626   return Result;
627 }
628 
629 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
630 /// templated submulticlass.  This returns a SubMultiClassRefTy with a null
631 /// Record* on error.
632 ///
633 ///  SubMultiClassRef ::= MultiClassID
634 ///  SubMultiClassRef ::= MultiClassID '<' ValueList '>'
635 ///
636 SubMultiClassReference TGParser::
637 ParseSubMultiClassReference(MultiClass *CurMC) {
638   SubMultiClassReference Result;
639   Result.RefRange.Start = Lex.getLoc();
640 
641   Result.MC = ParseMultiClassID();
642   if (!Result.MC) return Result;
643 
644   // If there is no template arg list, we're done.
645   if (!consume(tgtok::less)) {
646     Result.RefRange.End = Lex.getLoc();
647     return Result;
648   }
649 
650   if (Lex.getCode() == tgtok::greater) {
651     TokError("subclass reference requires a non-empty list of template values");
652     Result.MC = nullptr;
653     return Result;
654   }
655 
656   ParseValueList(Result.TemplateArgs, &CurMC->Rec, &Result.MC->Rec);
657   if (Result.TemplateArgs.empty()) {
658     Result.MC = nullptr;   // Error parsing value list.
659     return Result;
660   }
661 
662   if (!consume(tgtok::greater)) {
663     TokError("expected '>' in template value list");
664     Result.MC = nullptr;
665     return Result;
666   }
667   Result.RefRange.End = Lex.getLoc();
668 
669   return Result;
670 }
671 
672 /// ParseRangePiece - Parse a bit/value range.
673 ///   RangePiece ::= INTVAL
674 ///   RangePiece ::= INTVAL '...' INTVAL
675 ///   RangePiece ::= INTVAL '-' INTVAL
676 ///   RangePiece ::= INTVAL INTVAL
677 // The last two forms are deprecated.
678 bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
679                                TypedInit *FirstItem) {
680   Init *CurVal = FirstItem;
681   if (!CurVal)
682     CurVal = ParseValue(nullptr);
683 
684   IntInit *II = dyn_cast_or_null<IntInit>(CurVal);
685   if (!II)
686     return TokError("expected integer or bitrange");
687 
688   int64_t Start = II->getValue();
689   int64_t End;
690 
691   if (Start < 0)
692     return TokError("invalid range, cannot be negative");
693 
694   switch (Lex.getCode()) {
695   default:
696     Ranges.push_back(Start);
697     return false;
698 
699   case tgtok::dotdotdot:
700   case tgtok::minus: {
701     Lex.Lex(); // eat
702 
703     Init *I_End = ParseValue(nullptr);
704     IntInit *II_End = dyn_cast_or_null<IntInit>(I_End);
705     if (!II_End) {
706       TokError("expected integer value as end of range");
707       return true;
708     }
709 
710     End = II_End->getValue();
711     break;
712   }
713   case tgtok::IntVal: {
714     End = -Lex.getCurIntVal();
715     Lex.Lex();
716     break;
717   }
718   }
719   if (End < 0)
720     return TokError("invalid range, cannot be negative");
721 
722   // Add to the range.
723   if (Start < End)
724     for (; Start <= End; ++Start)
725       Ranges.push_back(Start);
726   else
727     for (; Start >= End; --Start)
728       Ranges.push_back(Start);
729   return false;
730 }
731 
732 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
733 ///
734 ///   RangeList ::= RangePiece (',' RangePiece)*
735 ///
736 void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) {
737   // Parse the first piece.
738   if (ParseRangePiece(Result)) {
739     Result.clear();
740     return;
741   }
742   while (consume(tgtok::comma))
743     // Parse the next range piece.
744     if (ParseRangePiece(Result)) {
745       Result.clear();
746       return;
747     }
748 }
749 
750 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
751 ///   OptionalRangeList ::= '<' RangeList '>'
752 ///   OptionalRangeList ::= /*empty*/
753 bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) {
754   SMLoc StartLoc = Lex.getLoc();
755   if (!consume(tgtok::less))
756     return false;
757 
758   // Parse the range list.
759   ParseRangeList(Ranges);
760   if (Ranges.empty()) return true;
761 
762   if (!consume(tgtok::greater)) {
763     TokError("expected '>' at end of range list");
764     return Error(StartLoc, "to match this '<'");
765   }
766   return false;
767 }
768 
769 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
770 ///   OptionalBitList ::= '{' RangeList '}'
771 ///   OptionalBitList ::= /*empty*/
772 bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) {
773   SMLoc StartLoc = Lex.getLoc();
774   if (!consume(tgtok::l_brace))
775     return false;
776 
777   // Parse the range list.
778   ParseRangeList(Ranges);
779   if (Ranges.empty()) return true;
780 
781   if (!consume(tgtok::r_brace)) {
782     TokError("expected '}' at end of bit list");
783     return Error(StartLoc, "to match this '{'");
784   }
785   return false;
786 }
787 
788 /// ParseType - Parse and return a tblgen type.  This returns null on error.
789 ///
790 ///   Type ::= STRING                       // string type
791 ///   Type ::= CODE                         // code type
792 ///   Type ::= BIT                          // bit type
793 ///   Type ::= BITS '<' INTVAL '>'          // bits<x> type
794 ///   Type ::= INT                          // int type
795 ///   Type ::= LIST '<' Type '>'            // list<x> type
796 ///   Type ::= DAG                          // dag type
797 ///   Type ::= ClassID                      // Record Type
798 ///
799 RecTy *TGParser::ParseType() {
800   switch (Lex.getCode()) {
801   default: TokError("Unknown token when expecting a type"); return nullptr;
802   case tgtok::String: Lex.Lex(); return StringRecTy::get();
803   case tgtok::Code:   Lex.Lex(); return CodeRecTy::get();
804   case tgtok::Bit:    Lex.Lex(); return BitRecTy::get();
805   case tgtok::Int:    Lex.Lex(); return IntRecTy::get();
806   case tgtok::Dag:    Lex.Lex(); return DagRecTy::get();
807   case tgtok::Id:
808     if (Record *R = ParseClassID()) return RecordRecTy::get(R);
809     TokError("unknown class name");
810     return nullptr;
811   case tgtok::Bits: {
812     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
813       TokError("expected '<' after bits type");
814       return nullptr;
815     }
816     if (Lex.Lex() != tgtok::IntVal) {  // Eat '<'
817       TokError("expected integer in bits<n> type");
818       return nullptr;
819     }
820     uint64_t Val = Lex.getCurIntVal();
821     if (Lex.Lex() != tgtok::greater) {  // Eat count.
822       TokError("expected '>' at end of bits<n> type");
823       return nullptr;
824     }
825     Lex.Lex();  // Eat '>'
826     return BitsRecTy::get(Val);
827   }
828   case tgtok::List: {
829     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
830       TokError("expected '<' after list type");
831       return nullptr;
832     }
833     Lex.Lex();  // Eat '<'
834     RecTy *SubType = ParseType();
835     if (!SubType) return nullptr;
836 
837     if (!consume(tgtok::greater)) {
838       TokError("expected '>' at end of list<ty> type");
839       return nullptr;
840     }
841     return ListRecTy::get(SubType);
842   }
843   }
844 }
845 
846 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
847 /// has already been read.
848 Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc,
849                              IDParseMode Mode) {
850   if (CurRec) {
851     if (const RecordVal *RV = CurRec->getValue(Name))
852       return VarInit::get(Name, RV->getType());
853   }
854 
855   if ((CurRec && CurRec->isClass()) || CurMultiClass) {
856     Init *TemplateArgName;
857     if (CurMultiClass) {
858       TemplateArgName =
859           QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
860     } else
861       TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
862 
863     Record *TemplateRec = CurMultiClass ? &CurMultiClass->Rec : CurRec;
864     if (TemplateRec->isTemplateArg(TemplateArgName)) {
865       const RecordVal *RV = TemplateRec->getValue(TemplateArgName);
866       assert(RV && "Template arg doesn't exist??");
867       return VarInit::get(TemplateArgName, RV->getType());
868     } else if (Name->getValue() == "NAME") {
869       return VarInit::get(TemplateArgName, StringRecTy::get());
870     }
871   }
872 
873   if (CurLocalScope)
874     if (Init *I = CurLocalScope->getVar(Name->getValue()))
875       return I;
876 
877   // If this is in a foreach loop, make sure it's not a loop iterator
878   for (const auto &L : Loops) {
879     if (L->IterVar) {
880       VarInit *IterVar = dyn_cast<VarInit>(L->IterVar);
881       if (IterVar && IterVar->getNameInit() == Name)
882         return IterVar;
883     }
884   }
885 
886   if (Mode == ParseNameMode)
887     return Name;
888 
889   if (Init *I = Records.getGlobal(Name->getValue()))
890     return I;
891 
892   // Allow self-references of concrete defs, but delay the lookup so that we
893   // get the correct type.
894   if (CurRec && !CurRec->isClass() && !CurMultiClass &&
895       CurRec->getNameInit() == Name)
896     return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType());
897 
898   Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'");
899   return nullptr;
900 }
901 
902 /// ParseOperation - Parse an operator.  This returns null on error.
903 ///
904 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
905 ///
906 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
907   switch (Lex.getCode()) {
908   default:
909     TokError("unknown operation");
910     return nullptr;
911   case tgtok::XHead:
912   case tgtok::XTail:
913   case tgtok::XSize:
914   case tgtok::XEmpty:
915   case tgtok::XCast:
916   case tgtok::XGetOp: {  // Value ::= !unop '(' Value ')'
917     UnOpInit::UnaryOp Code;
918     RecTy *Type = nullptr;
919 
920     switch (Lex.getCode()) {
921     default: llvm_unreachable("Unhandled code!");
922     case tgtok::XCast:
923       Lex.Lex();  // eat the operation
924       Code = UnOpInit::CAST;
925 
926       Type = ParseOperatorType();
927 
928       if (!Type) {
929         TokError("did not get type for unary operator");
930         return nullptr;
931       }
932 
933       break;
934     case tgtok::XHead:
935       Lex.Lex();  // eat the operation
936       Code = UnOpInit::HEAD;
937       break;
938     case tgtok::XTail:
939       Lex.Lex();  // eat the operation
940       Code = UnOpInit::TAIL;
941       break;
942     case tgtok::XSize:
943       Lex.Lex();
944       Code = UnOpInit::SIZE;
945       Type = IntRecTy::get();
946       break;
947     case tgtok::XEmpty:
948       Lex.Lex();  // eat the operation
949       Code = UnOpInit::EMPTY;
950       Type = IntRecTy::get();
951       break;
952     case tgtok::XGetOp:
953       Lex.Lex();  // eat the operation
954       if (Lex.getCode() == tgtok::less) {
955         // Parse an optional type suffix, so that you can say
956         // !getop<BaseClass>(someDag) as a shorthand for
957         // !cast<BaseClass>(!getop(someDag)).
958         Type = ParseOperatorType();
959 
960         if (!Type) {
961           TokError("did not get type for unary operator");
962           return nullptr;
963         }
964 
965         if (!isa<RecordRecTy>(Type)) {
966           TokError("type for !getop must be a record type");
967           // but keep parsing, to consume the operand
968         }
969       } else {
970         Type = RecordRecTy::get({});
971       }
972       Code = UnOpInit::GETOP;
973       break;
974     }
975     if (!consume(tgtok::l_paren)) {
976       TokError("expected '(' after unary operator");
977       return nullptr;
978     }
979 
980     Init *LHS = ParseValue(CurRec);
981     if (!LHS) return nullptr;
982 
983     if (Code == UnOpInit::HEAD ||
984         Code == UnOpInit::TAIL ||
985         Code == UnOpInit::EMPTY) {
986       ListInit *LHSl = dyn_cast<ListInit>(LHS);
987       StringInit *LHSs = dyn_cast<StringInit>(LHS);
988       TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
989       if (!LHSl && !LHSs && !LHSt) {
990         TokError("expected list or string type argument in unary operator");
991         return nullptr;
992       }
993       if (LHSt) {
994         ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
995         StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
996         if (!LType && !SType) {
997           TokError("expected list or string type argument in unary operator");
998           return nullptr;
999         }
1000       }
1001 
1002       if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL ||
1003           Code == UnOpInit::SIZE) {
1004         if (!LHSl && !LHSt) {
1005           TokError("expected list type argument in unary operator");
1006           return nullptr;
1007         }
1008       }
1009 
1010       if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
1011         if (LHSl && LHSl->empty()) {
1012           TokError("empty list argument in unary operator");
1013           return nullptr;
1014         }
1015         if (LHSl) {
1016           Init *Item = LHSl->getElement(0);
1017           TypedInit *Itemt = dyn_cast<TypedInit>(Item);
1018           if (!Itemt) {
1019             TokError("untyped list element in unary operator");
1020             return nullptr;
1021           }
1022           Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
1023                                           : ListRecTy::get(Itemt->getType());
1024         } else {
1025           assert(LHSt && "expected list type argument in unary operator");
1026           ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1027           if (!LType) {
1028             TokError("expected list type argument in unary operator");
1029             return nullptr;
1030           }
1031           Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
1032         }
1033       }
1034     }
1035 
1036     if (!consume(tgtok::r_paren)) {
1037       TokError("expected ')' in unary operator");
1038       return nullptr;
1039     }
1040     return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec);
1041   }
1042 
1043   case tgtok::XIsA: {
1044     // Value ::= !isa '<' Type '>' '(' Value ')'
1045     Lex.Lex(); // eat the operation
1046 
1047     RecTy *Type = ParseOperatorType();
1048     if (!Type)
1049       return nullptr;
1050 
1051     if (!consume(tgtok::l_paren)) {
1052       TokError("expected '(' after type of !isa");
1053       return nullptr;
1054     }
1055 
1056     Init *LHS = ParseValue(CurRec);
1057     if (!LHS)
1058       return nullptr;
1059 
1060     if (!consume(tgtok::r_paren)) {
1061       TokError("expected ')' in !isa");
1062       return nullptr;
1063     }
1064 
1065     return (IsAOpInit::get(Type, LHS))->Fold();
1066   }
1067 
1068   case tgtok::XConcat:
1069   case tgtok::XADD:
1070   case tgtok::XMUL:
1071   case tgtok::XAND:
1072   case tgtok::XOR:
1073   case tgtok::XSRA:
1074   case tgtok::XSRL:
1075   case tgtok::XSHL:
1076   case tgtok::XEq:
1077   case tgtok::XNe:
1078   case tgtok::XLe:
1079   case tgtok::XLt:
1080   case tgtok::XGe:
1081   case tgtok::XGt:
1082   case tgtok::XListConcat:
1083   case tgtok::XListSplat:
1084   case tgtok::XStrConcat:
1085   case tgtok::XSetOp: {  // Value ::= !binop '(' Value ',' Value ')'
1086     tgtok::TokKind OpTok = Lex.getCode();
1087     SMLoc OpLoc = Lex.getLoc();
1088     Lex.Lex();  // eat the operation
1089 
1090     BinOpInit::BinaryOp Code;
1091     switch (OpTok) {
1092     default: llvm_unreachable("Unhandled code!");
1093     case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
1094     case tgtok::XADD:    Code = BinOpInit::ADD; break;
1095     case tgtok::XMUL:    Code = BinOpInit::MUL; break;
1096     case tgtok::XAND:    Code = BinOpInit::AND; break;
1097     case tgtok::XOR:     Code = BinOpInit::OR; break;
1098     case tgtok::XSRA:    Code = BinOpInit::SRA; break;
1099     case tgtok::XSRL:    Code = BinOpInit::SRL; break;
1100     case tgtok::XSHL:    Code = BinOpInit::SHL; break;
1101     case tgtok::XEq:     Code = BinOpInit::EQ; break;
1102     case tgtok::XNe:     Code = BinOpInit::NE; break;
1103     case tgtok::XLe:     Code = BinOpInit::LE; break;
1104     case tgtok::XLt:     Code = BinOpInit::LT; break;
1105     case tgtok::XGe:     Code = BinOpInit::GE; break;
1106     case tgtok::XGt:     Code = BinOpInit::GT; break;
1107     case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break;
1108     case tgtok::XListSplat: Code = BinOpInit::LISTSPLAT; break;
1109     case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
1110     case tgtok::XSetOp: Code = BinOpInit::SETOP; break;
1111     }
1112 
1113     RecTy *Type = nullptr;
1114     RecTy *ArgType = nullptr;
1115     switch (OpTok) {
1116     default:
1117       llvm_unreachable("Unhandled code!");
1118     case tgtok::XConcat:
1119     case tgtok::XSetOp:
1120       Type = DagRecTy::get();
1121       ArgType = DagRecTy::get();
1122       break;
1123     case tgtok::XAND:
1124     case tgtok::XOR:
1125     case tgtok::XSRA:
1126     case tgtok::XSRL:
1127     case tgtok::XSHL:
1128     case tgtok::XADD:
1129     case tgtok::XMUL:
1130       Type = IntRecTy::get();
1131       ArgType = IntRecTy::get();
1132       break;
1133     case tgtok::XEq:
1134     case tgtok::XNe:
1135       Type = BitRecTy::get();
1136       // ArgType for Eq / Ne is not known at this point
1137       break;
1138     case tgtok::XLe:
1139     case tgtok::XLt:
1140     case tgtok::XGe:
1141     case tgtok::XGt:
1142       Type = BitRecTy::get();
1143       ArgType = IntRecTy::get();
1144       break;
1145     case tgtok::XListConcat:
1146       // We don't know the list type until we parse the first argument
1147       ArgType = ItemType;
1148       break;
1149     case tgtok::XListSplat:
1150       // Can't do any typechecking until we parse the first argument.
1151       break;
1152     case tgtok::XStrConcat:
1153       Type = StringRecTy::get();
1154       ArgType = StringRecTy::get();
1155       break;
1156     }
1157 
1158     if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1159       Error(OpLoc, Twine("expected value of type '") +
1160                    ItemType->getAsString() + "', got '" +
1161                    Type->getAsString() + "'");
1162       return nullptr;
1163     }
1164 
1165     if (!consume(tgtok::l_paren)) {
1166       TokError("expected '(' after binary operator");
1167       return nullptr;
1168     }
1169 
1170     SmallVector<Init*, 2> InitList;
1171 
1172     for (;;) {
1173       SMLoc InitLoc = Lex.getLoc();
1174       InitList.push_back(ParseValue(CurRec, ArgType));
1175       if (!InitList.back()) return nullptr;
1176 
1177       TypedInit *InitListBack = dyn_cast<TypedInit>(InitList.back());
1178       if (!InitListBack) {
1179         Error(OpLoc, Twine("expected value to be a typed value, got '" +
1180                            InitList.back()->getAsString() + "'"));
1181         return nullptr;
1182       }
1183       RecTy *ListType = InitListBack->getType();
1184       if (!ArgType) {
1185         ArgType = ListType;
1186 
1187         switch (Code) {
1188         case BinOpInit::LISTCONCAT:
1189           if (!isa<ListRecTy>(ArgType)) {
1190             Error(InitLoc, Twine("expected a list, got value of type '") +
1191                            ArgType->getAsString() + "'");
1192             return nullptr;
1193           }
1194           break;
1195         case BinOpInit::LISTSPLAT:
1196           if (ItemType && InitList.size() == 1) {
1197             if (!isa<ListRecTy>(ItemType)) {
1198               Error(OpLoc,
1199                     Twine("expected output type to be a list, got type '") +
1200                         ItemType->getAsString() + "'");
1201               return nullptr;
1202             }
1203             if (!ArgType->getListTy()->typeIsConvertibleTo(ItemType)) {
1204               Error(OpLoc, Twine("expected first arg type to be '") +
1205                                ArgType->getAsString() +
1206                                "', got value of type '" +
1207                                cast<ListRecTy>(ItemType)
1208                                    ->getElementType()
1209                                    ->getAsString() +
1210                                "'");
1211               return nullptr;
1212             }
1213           }
1214           if (InitList.size() == 2 && !isa<IntRecTy>(ArgType)) {
1215             Error(InitLoc, Twine("expected second parameter to be an int, got "
1216                                  "value of type '") +
1217                                ArgType->getAsString() + "'");
1218             return nullptr;
1219           }
1220           ArgType = nullptr; // Broken invariant: types not identical.
1221           break;
1222         case BinOpInit::EQ:
1223         case BinOpInit::NE:
1224           if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
1225               !ArgType->typeIsConvertibleTo(StringRecTy::get())) {
1226             Error(InitLoc, Twine("expected int, bits, or string; got value of "
1227                                  "type '") + ArgType->getAsString() + "'");
1228             return nullptr;
1229           }
1230           break;
1231         default: llvm_unreachable("other ops have fixed argument types");
1232         }
1233       } else {
1234         RecTy *Resolved = resolveTypes(ArgType, ListType);
1235         if (!Resolved) {
1236           Error(InitLoc, Twine("expected value of type '") +
1237                              ArgType->getAsString() + "', got '" +
1238                              ListType->getAsString() + "'");
1239           return nullptr;
1240         }
1241         if (Code != BinOpInit::ADD && Code != BinOpInit::AND &&
1242             Code != BinOpInit::OR && Code != BinOpInit::SRA &&
1243             Code != BinOpInit::SRL && Code != BinOpInit::SHL &&
1244             Code != BinOpInit::MUL)
1245           ArgType = Resolved;
1246       }
1247 
1248       // Deal with BinOps whose arguments have different types, by
1249       // rewriting ArgType in between them.
1250       switch (Code) {
1251         case BinOpInit::SETOP:
1252           // After parsing the first dag argument, switch to expecting
1253           // a record, with no restriction on its superclasses.
1254           ArgType = RecordRecTy::get({});
1255           break;
1256         default:
1257           break;
1258       }
1259 
1260       if (!consume(tgtok::comma))
1261         break;
1262     }
1263 
1264     if (!consume(tgtok::r_paren)) {
1265       TokError("expected ')' in operator");
1266       return nullptr;
1267     }
1268 
1269     // listconcat returns a list with type of the argument.
1270     if (Code == BinOpInit::LISTCONCAT)
1271       Type = ArgType;
1272     // listsplat returns a list of type of the *first* argument.
1273     if (Code == BinOpInit::LISTSPLAT)
1274       Type = cast<TypedInit>(InitList.front())->getType()->getListTy();
1275 
1276     // We allow multiple operands to associative operators like !strconcat as
1277     // shorthand for nesting them.
1278     if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT ||
1279         Code == BinOpInit::CONCAT || Code == BinOpInit::ADD ||
1280         Code == BinOpInit::AND || Code == BinOpInit::OR ||
1281         Code == BinOpInit::MUL) {
1282       while (InitList.size() > 2) {
1283         Init *RHS = InitList.pop_back_val();
1284         RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec);
1285         InitList.back() = RHS;
1286       }
1287     }
1288 
1289     if (InitList.size() == 2)
1290       return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
1291           ->Fold(CurRec);
1292 
1293     Error(OpLoc, "expected two operands to operator");
1294     return nullptr;
1295   }
1296 
1297   case tgtok::XForEach: {
1298     // Value ::= !foreach '(' Id ',' Value ',' Value ')'
1299     SMLoc OpLoc = Lex.getLoc();
1300     Lex.Lex(); // eat the operation
1301     if (Lex.getCode() != tgtok::l_paren) {
1302       TokError("expected '(' after !foreach");
1303       return nullptr;
1304     }
1305 
1306     if (Lex.Lex() != tgtok::Id) { // eat the '('
1307       TokError("first argument of !foreach must be an identifier");
1308       return nullptr;
1309     }
1310 
1311     Init *LHS = StringInit::get(Lex.getCurStrVal());
1312     Lex.Lex();
1313 
1314     if (CurRec && CurRec->getValue(LHS)) {
1315       TokError((Twine("iteration variable '") + LHS->getAsString() +
1316                 "' already defined")
1317                    .str());
1318       return nullptr;
1319     }
1320 
1321     if (!consume(tgtok::comma)) { // eat the id
1322       TokError("expected ',' in ternary operator");
1323       return nullptr;
1324     }
1325 
1326     Init *MHS = ParseValue(CurRec);
1327     if (!MHS)
1328       return nullptr;
1329 
1330     if (!consume(tgtok::comma)) {
1331       TokError("expected ',' in ternary operator");
1332       return nullptr;
1333     }
1334 
1335     TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1336     if (!MHSt) {
1337       TokError("could not get type of !foreach input");
1338       return nullptr;
1339     }
1340 
1341     RecTy *InEltType = nullptr;
1342     RecTy *OutEltType = nullptr;
1343     bool IsDAG = false;
1344 
1345     if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) {
1346       InEltType = InListTy->getElementType();
1347       if (ItemType) {
1348         if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) {
1349           OutEltType = OutListTy->getElementType();
1350         } else {
1351           Error(OpLoc,
1352                 "expected value of type '" + Twine(ItemType->getAsString()) +
1353                 "', but got !foreach of list type");
1354           return nullptr;
1355         }
1356       }
1357     } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) {
1358       InEltType = InDagTy;
1359       if (ItemType && !isa<DagRecTy>(ItemType)) {
1360         Error(OpLoc,
1361               "expected value of type '" + Twine(ItemType->getAsString()) +
1362               "', but got !foreach of dag type");
1363         return nullptr;
1364       }
1365       IsDAG = true;
1366     } else {
1367       TokError("!foreach must have list or dag input");
1368       return nullptr;
1369     }
1370 
1371     // We need to create a temporary record to provide a scope for the
1372     // iteration variable.
1373     std::unique_ptr<Record> ParseRecTmp;
1374     Record *ParseRec = CurRec;
1375     if (!ParseRec) {
1376       ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1377       ParseRec = ParseRecTmp.get();
1378     }
1379 
1380     ParseRec->addValue(RecordVal(LHS, InEltType, false));
1381     Init *RHS = ParseValue(ParseRec, OutEltType);
1382     ParseRec->removeValue(LHS);
1383     if (!RHS)
1384       return nullptr;
1385 
1386     if (!consume(tgtok::r_paren)) {
1387       TokError("expected ')' in binary operator");
1388       return nullptr;
1389     }
1390 
1391     RecTy *OutType;
1392     if (IsDAG) {
1393       OutType = InEltType;
1394     } else {
1395       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1396       if (!RHSt) {
1397         TokError("could not get type of !foreach result");
1398         return nullptr;
1399       }
1400       OutType = RHSt->getType()->getListTy();
1401     }
1402 
1403     return (TernOpInit::get(TernOpInit::FOREACH, LHS, MHS, RHS, OutType))
1404         ->Fold(CurRec);
1405   }
1406 
1407   case tgtok::XDag:
1408   case tgtok::XIf:
1409   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1410     TernOpInit::TernaryOp Code;
1411     RecTy *Type = nullptr;
1412 
1413     tgtok::TokKind LexCode = Lex.getCode();
1414     Lex.Lex();  // eat the operation
1415     switch (LexCode) {
1416     default: llvm_unreachable("Unhandled code!");
1417     case tgtok::XDag:
1418       Code = TernOpInit::DAG;
1419       Type = DagRecTy::get();
1420       ItemType = nullptr;
1421       break;
1422     case tgtok::XIf:
1423       Code = TernOpInit::IF;
1424       break;
1425     case tgtok::XSubst:
1426       Code = TernOpInit::SUBST;
1427       break;
1428     }
1429     if (!consume(tgtok::l_paren)) {
1430       TokError("expected '(' after ternary operator");
1431       return nullptr;
1432     }
1433 
1434     Init *LHS = ParseValue(CurRec);
1435     if (!LHS) return nullptr;
1436 
1437     if (!consume(tgtok::comma)) {
1438       TokError("expected ',' in ternary operator");
1439       return nullptr;
1440     }
1441 
1442     SMLoc MHSLoc = Lex.getLoc();
1443     Init *MHS = ParseValue(CurRec, ItemType);
1444     if (!MHS)
1445       return nullptr;
1446 
1447     if (!consume(tgtok::comma)) {
1448       TokError("expected ',' in ternary operator");
1449       return nullptr;
1450     }
1451 
1452     SMLoc RHSLoc = Lex.getLoc();
1453     Init *RHS = ParseValue(CurRec, ItemType);
1454     if (!RHS)
1455       return nullptr;
1456 
1457     if (!consume(tgtok::r_paren)) {
1458       TokError("expected ')' in binary operator");
1459       return nullptr;
1460     }
1461 
1462     switch (LexCode) {
1463     default: llvm_unreachable("Unhandled code!");
1464     case tgtok::XDag: {
1465       TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1466       if (!MHSt && !isa<UnsetInit>(MHS)) {
1467         Error(MHSLoc, "could not determine type of the child list in !dag");
1468         return nullptr;
1469       }
1470       if (MHSt && !isa<ListRecTy>(MHSt->getType())) {
1471         Error(MHSLoc, Twine("expected list of children, got type '") +
1472                           MHSt->getType()->getAsString() + "'");
1473         return nullptr;
1474       }
1475 
1476       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1477       if (!RHSt && !isa<UnsetInit>(RHS)) {
1478         Error(RHSLoc, "could not determine type of the name list in !dag");
1479         return nullptr;
1480       }
1481       if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) {
1482         Error(RHSLoc, Twine("expected list<string>, got type '") +
1483                           RHSt->getType()->getAsString() + "'");
1484         return nullptr;
1485       }
1486 
1487       if (!MHSt && !RHSt) {
1488         Error(MHSLoc,
1489               "cannot have both unset children and unset names in !dag");
1490         return nullptr;
1491       }
1492       break;
1493     }
1494     case tgtok::XIf: {
1495       RecTy *MHSTy = nullptr;
1496       RecTy *RHSTy = nullptr;
1497 
1498       if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1499         MHSTy = MHSt->getType();
1500       if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1501         MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1502       if (isa<BitInit>(MHS))
1503         MHSTy = BitRecTy::get();
1504 
1505       if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1506         RHSTy = RHSt->getType();
1507       if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1508         RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1509       if (isa<BitInit>(RHS))
1510         RHSTy = BitRecTy::get();
1511 
1512       // For UnsetInit, it's typed from the other hand.
1513       if (isa<UnsetInit>(MHS))
1514         MHSTy = RHSTy;
1515       if (isa<UnsetInit>(RHS))
1516         RHSTy = MHSTy;
1517 
1518       if (!MHSTy || !RHSTy) {
1519         TokError("could not get type for !if");
1520         return nullptr;
1521       }
1522 
1523       Type = resolveTypes(MHSTy, RHSTy);
1524       if (!Type) {
1525         TokError(Twine("inconsistent types '") + MHSTy->getAsString() +
1526                  "' and '" + RHSTy->getAsString() + "' for !if");
1527         return nullptr;
1528       }
1529       break;
1530     }
1531     case tgtok::XSubst: {
1532       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1533       if (!RHSt) {
1534         TokError("could not get type for !subst");
1535         return nullptr;
1536       }
1537       Type = RHSt->getType();
1538       break;
1539     }
1540     }
1541     return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
1542   }
1543 
1544   case tgtok::XCond:
1545     return ParseOperationCond(CurRec, ItemType);
1546 
1547   case tgtok::XFoldl: {
1548     // Value ::= !foldl '(' Value ',' Value ',' Id ',' Id ',' Expr ')'
1549     Lex.Lex(); // eat the operation
1550     if (!consume(tgtok::l_paren)) {
1551       TokError("expected '(' after !foldl");
1552       return nullptr;
1553     }
1554 
1555     Init *StartUntyped = ParseValue(CurRec);
1556     if (!StartUntyped)
1557       return nullptr;
1558 
1559     TypedInit *Start = dyn_cast<TypedInit>(StartUntyped);
1560     if (!Start) {
1561       TokError(Twine("could not get type of !foldl start: '") +
1562                StartUntyped->getAsString() + "'");
1563       return nullptr;
1564     }
1565 
1566     if (!consume(tgtok::comma)) {
1567       TokError("expected ',' in !foldl");
1568       return nullptr;
1569     }
1570 
1571     Init *ListUntyped = ParseValue(CurRec);
1572     if (!ListUntyped)
1573       return nullptr;
1574 
1575     TypedInit *List = dyn_cast<TypedInit>(ListUntyped);
1576     if (!List) {
1577       TokError(Twine("could not get type of !foldl list: '") +
1578                ListUntyped->getAsString() + "'");
1579       return nullptr;
1580     }
1581 
1582     ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType());
1583     if (!ListType) {
1584       TokError(Twine("!foldl list must be a list, but is of type '") +
1585                List->getType()->getAsString());
1586       return nullptr;
1587     }
1588 
1589     if (Lex.getCode() != tgtok::comma) {
1590       TokError("expected ',' in !foldl");
1591       return nullptr;
1592     }
1593 
1594     if (Lex.Lex() != tgtok::Id) { // eat the ','
1595       TokError("third argument of !foldl must be an identifier");
1596       return nullptr;
1597     }
1598 
1599     Init *A = StringInit::get(Lex.getCurStrVal());
1600     if (CurRec && CurRec->getValue(A)) {
1601       TokError((Twine("left !foldl variable '") + A->getAsString() +
1602                 "' already defined")
1603                    .str());
1604       return nullptr;
1605     }
1606 
1607     if (Lex.Lex() != tgtok::comma) { // eat the id
1608       TokError("expected ',' in !foldl");
1609       return nullptr;
1610     }
1611 
1612     if (Lex.Lex() != tgtok::Id) { // eat the ','
1613       TokError("fourth argument of !foldl must be an identifier");
1614       return nullptr;
1615     }
1616 
1617     Init *B = StringInit::get(Lex.getCurStrVal());
1618     if (CurRec && CurRec->getValue(B)) {
1619       TokError((Twine("right !foldl variable '") + B->getAsString() +
1620                 "' already defined")
1621                    .str());
1622       return nullptr;
1623     }
1624 
1625     if (Lex.Lex() != tgtok::comma) { // eat the id
1626       TokError("expected ',' in !foldl");
1627       return nullptr;
1628     }
1629     Lex.Lex(); // eat the ','
1630 
1631     // We need to create a temporary record to provide a scope for the
1632     // two variables.
1633     std::unique_ptr<Record> ParseRecTmp;
1634     Record *ParseRec = CurRec;
1635     if (!ParseRec) {
1636       ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1637       ParseRec = ParseRecTmp.get();
1638     }
1639 
1640     ParseRec->addValue(RecordVal(A, Start->getType(), false));
1641     ParseRec->addValue(RecordVal(B, ListType->getElementType(), false));
1642     Init *ExprUntyped = ParseValue(ParseRec);
1643     ParseRec->removeValue(A);
1644     ParseRec->removeValue(B);
1645     if (!ExprUntyped)
1646       return nullptr;
1647 
1648     TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped);
1649     if (!Expr) {
1650       TokError("could not get type of !foldl expression");
1651       return nullptr;
1652     }
1653 
1654     if (Expr->getType() != Start->getType()) {
1655       TokError(Twine("!foldl expression must be of same type as start (") +
1656                Start->getType()->getAsString() + "), but is of type " +
1657                Expr->getType()->getAsString());
1658       return nullptr;
1659     }
1660 
1661     if (!consume(tgtok::r_paren)) {
1662       TokError("expected ')' in fold operator");
1663       return nullptr;
1664     }
1665 
1666     return FoldOpInit::get(Start, List, A, B, Expr, Start->getType())
1667         ->Fold(CurRec);
1668   }
1669   }
1670 }
1671 
1672 /// ParseOperatorType - Parse a type for an operator.  This returns
1673 /// null on error.
1674 ///
1675 /// OperatorType ::= '<' Type '>'
1676 ///
1677 RecTy *TGParser::ParseOperatorType() {
1678   RecTy *Type = nullptr;
1679 
1680   if (!consume(tgtok::less)) {
1681     TokError("expected type name for operator");
1682     return nullptr;
1683   }
1684 
1685   Type = ParseType();
1686 
1687   if (!Type) {
1688     TokError("expected type name for operator");
1689     return nullptr;
1690   }
1691 
1692   if (!consume(tgtok::greater)) {
1693     TokError("expected type name for operator");
1694     return nullptr;
1695   }
1696 
1697   return Type;
1698 }
1699 
1700 Init *TGParser::ParseOperationCond(Record *CurRec, RecTy *ItemType) {
1701   Lex.Lex();  // eat the operation 'cond'
1702 
1703   if (!consume(tgtok::l_paren)) {
1704     TokError("expected '(' after !cond operator");
1705     return nullptr;
1706   }
1707 
1708   // Parse through '[Case: Val,]+'
1709   SmallVector<Init *, 4> Case;
1710   SmallVector<Init *, 4> Val;
1711   while (true) {
1712     if (consume(tgtok::r_paren))
1713       break;
1714 
1715     Init *V = ParseValue(CurRec);
1716     if (!V)
1717       return nullptr;
1718     Case.push_back(V);
1719 
1720     if (!consume(tgtok::colon)) {
1721       TokError("expected ':'  following a condition in !cond operator");
1722       return nullptr;
1723     }
1724 
1725     V = ParseValue(CurRec, ItemType);
1726     if (!V)
1727       return nullptr;
1728     Val.push_back(V);
1729 
1730     if (consume(tgtok::r_paren))
1731       break;
1732 
1733     if (!consume(tgtok::comma)) {
1734       TokError("expected ',' or ')' following a value in !cond operator");
1735       return nullptr;
1736     }
1737   }
1738 
1739   if (Case.size() < 1) {
1740     TokError("there should be at least 1 'condition : value' in the !cond operator");
1741     return nullptr;
1742   }
1743 
1744   // resolve type
1745   RecTy *Type = nullptr;
1746   for (Init *V : Val) {
1747     RecTy *VTy = nullptr;
1748     if (TypedInit *Vt = dyn_cast<TypedInit>(V))
1749       VTy = Vt->getType();
1750     if (BitsInit *Vbits = dyn_cast<BitsInit>(V))
1751       VTy = BitsRecTy::get(Vbits->getNumBits());
1752     if (isa<BitInit>(V))
1753       VTy = BitRecTy::get();
1754 
1755     if (Type == nullptr) {
1756       if (!isa<UnsetInit>(V))
1757         Type = VTy;
1758     } else {
1759       if (!isa<UnsetInit>(V)) {
1760         RecTy *RType = resolveTypes(Type, VTy);
1761         if (!RType) {
1762           TokError(Twine("inconsistent types '") + Type->getAsString() +
1763                          "' and '" + VTy->getAsString() + "' for !cond");
1764           return nullptr;
1765         }
1766         Type = RType;
1767       }
1768     }
1769   }
1770 
1771   if (!Type) {
1772     TokError("could not determine type for !cond from its arguments");
1773     return nullptr;
1774   }
1775   return CondOpInit::get(Case, Val, Type)->Fold(CurRec);
1776 }
1777 
1778 /// ParseSimpleValue - Parse a tblgen value.  This returns null on error.
1779 ///
1780 ///   SimpleValue ::= IDValue
1781 ///   SimpleValue ::= INTVAL
1782 ///   SimpleValue ::= STRVAL+
1783 ///   SimpleValue ::= CODEFRAGMENT
1784 ///   SimpleValue ::= '?'
1785 ///   SimpleValue ::= '{' ValueList '}'
1786 ///   SimpleValue ::= ID '<' ValueListNE '>'
1787 ///   SimpleValue ::= '[' ValueList ']'
1788 ///   SimpleValue ::= '(' IDValue DagArgList ')'
1789 ///   SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1790 ///   SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1791 ///   SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1792 ///   SimpleValue ::= SRATOK '(' Value ',' Value ')'
1793 ///   SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1794 ///   SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1795 ///   SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
1796 ///   SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1797 ///   SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
1798 ///
1799 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1800                                  IDParseMode Mode) {
1801   Init *R = nullptr;
1802   switch (Lex.getCode()) {
1803   default: TokError("Unknown token when parsing a value"); break;
1804   case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1805   case tgtok::BinaryIntVal: {
1806     auto BinaryVal = Lex.getCurBinaryIntVal();
1807     SmallVector<Init*, 16> Bits(BinaryVal.second);
1808     for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1809       Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1810     R = BitsInit::get(Bits);
1811     Lex.Lex();
1812     break;
1813   }
1814   case tgtok::StrVal: {
1815     std::string Val = Lex.getCurStrVal();
1816     Lex.Lex();
1817 
1818     // Handle multiple consecutive concatenated strings.
1819     while (Lex.getCode() == tgtok::StrVal) {
1820       Val += Lex.getCurStrVal();
1821       Lex.Lex();
1822     }
1823 
1824     R = StringInit::get(Val);
1825     break;
1826   }
1827   case tgtok::CodeFragment:
1828     R = CodeInit::get(Lex.getCurStrVal(), Lex.getLoc());
1829     Lex.Lex();
1830     break;
1831   case tgtok::question:
1832     R = UnsetInit::get();
1833     Lex.Lex();
1834     break;
1835   case tgtok::Id: {
1836     SMLoc NameLoc = Lex.getLoc();
1837     StringInit *Name = StringInit::get(Lex.getCurStrVal());
1838     if (Lex.Lex() != tgtok::less)  // consume the Id.
1839       return ParseIDValue(CurRec, Name, NameLoc, Mode);    // Value ::= IDValue
1840 
1841     // Value ::= ID '<' ValueListNE '>'
1842     if (Lex.Lex() == tgtok::greater) {
1843       TokError("expected non-empty value list");
1844       return nullptr;
1845     }
1846 
1847     // This is a CLASS<initvalslist> expression.  This is supposed to synthesize
1848     // a new anonymous definition, deriving from CLASS<initvalslist> with no
1849     // body.
1850     Record *Class = Records.getClass(Name->getValue());
1851     if (!Class) {
1852       Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'");
1853       return nullptr;
1854     }
1855 
1856     SmallVector<Init *, 8> Args;
1857     ParseValueList(Args, CurRec, Class);
1858     if (Args.empty()) return nullptr;
1859 
1860     if (!consume(tgtok::greater)) {
1861       TokError("expected '>' at end of value list");
1862       return nullptr;
1863     }
1864 
1865     // Typecheck the template arguments list
1866     ArrayRef<Init *> ExpectedArgs = Class->getTemplateArgs();
1867     if (ExpectedArgs.size() < Args.size()) {
1868       Error(NameLoc,
1869             "More template args specified than expected");
1870       return nullptr;
1871     }
1872 
1873     for (unsigned i = 0, e = ExpectedArgs.size(); i != e; ++i) {
1874       RecordVal *ExpectedArg = Class->getValue(ExpectedArgs[i]);
1875       if (i < Args.size()) {
1876         if (TypedInit *TI = dyn_cast<TypedInit>(Args[i])) {
1877           RecTy *ExpectedType = ExpectedArg->getType();
1878           if (!TI->getType()->typeIsConvertibleTo(ExpectedType)) {
1879             Error(NameLoc,
1880                   "Value specified for template argument #" + Twine(i) + " (" +
1881                   ExpectedArg->getNameInitAsString() + ") is of type '" +
1882                   TI->getType()->getAsString() + "', expected '" +
1883                   ExpectedType->getAsString() + "': " + TI->getAsString());
1884             return nullptr;
1885           }
1886           continue;
1887         }
1888       } else if (ExpectedArg->getValue()->isComplete())
1889         continue;
1890 
1891       Error(NameLoc,
1892             "Value not specified for template argument #" + Twine(i) + " (" +
1893             ExpectedArgs[i]->getAsUnquotedString() + ")");
1894       return nullptr;
1895     }
1896 
1897     return VarDefInit::get(Class, Args)->Fold();
1898   }
1899   case tgtok::l_brace: {           // Value ::= '{' ValueList '}'
1900     SMLoc BraceLoc = Lex.getLoc();
1901     Lex.Lex(); // eat the '{'
1902     SmallVector<Init*, 16> Vals;
1903 
1904     if (Lex.getCode() != tgtok::r_brace) {
1905       ParseValueList(Vals, CurRec);
1906       if (Vals.empty()) return nullptr;
1907     }
1908     if (!consume(tgtok::r_brace)) {
1909       TokError("expected '}' at end of bit list value");
1910       return nullptr;
1911     }
1912 
1913     SmallVector<Init *, 16> NewBits;
1914 
1915     // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1916     // first.  We'll first read everything in to a vector, then we can reverse
1917     // it to get the bits in the correct order for the BitsInit value.
1918     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1919       // FIXME: The following two loops would not be duplicated
1920       //        if the API was a little more orthogonal.
1921 
1922       // bits<n> values are allowed to initialize n bits.
1923       if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1924         for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1925           NewBits.push_back(BI->getBit((e - i) - 1));
1926         continue;
1927       }
1928       // bits<n> can also come from variable initializers.
1929       if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
1930         if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
1931           for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
1932             NewBits.push_back(VI->getBit((e - i) - 1));
1933           continue;
1934         }
1935         // Fallthrough to try convert this to a bit.
1936       }
1937       // All other values must be convertible to just a single bit.
1938       Init *Bit = Vals[i]->getCastTo(BitRecTy::get());
1939       if (!Bit) {
1940         Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
1941               ") is not convertable to a bit");
1942         return nullptr;
1943       }
1944       NewBits.push_back(Bit);
1945     }
1946     std::reverse(NewBits.begin(), NewBits.end());
1947     return BitsInit::get(NewBits);
1948   }
1949   case tgtok::l_square: {          // Value ::= '[' ValueList ']'
1950     Lex.Lex(); // eat the '['
1951     SmallVector<Init*, 16> Vals;
1952 
1953     RecTy *DeducedEltTy = nullptr;
1954     ListRecTy *GivenListTy = nullptr;
1955 
1956     if (ItemType) {
1957       ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1958       if (!ListType) {
1959         TokError(Twine("Type mismatch for list, expected list type, got ") +
1960                  ItemType->getAsString());
1961         return nullptr;
1962       }
1963       GivenListTy = ListType;
1964     }
1965 
1966     if (Lex.getCode() != tgtok::r_square) {
1967       ParseValueList(Vals, CurRec, nullptr,
1968                      GivenListTy ? GivenListTy->getElementType() : nullptr);
1969       if (Vals.empty()) return nullptr;
1970     }
1971     if (!consume(tgtok::r_square)) {
1972       TokError("expected ']' at end of list value");
1973       return nullptr;
1974     }
1975 
1976     RecTy *GivenEltTy = nullptr;
1977     if (consume(tgtok::less)) {
1978       // Optional list element type
1979       GivenEltTy = ParseType();
1980       if (!GivenEltTy) {
1981         // Couldn't parse element type
1982         return nullptr;
1983       }
1984 
1985       if (!consume(tgtok::greater)) {
1986         TokError("expected '>' at end of list element type");
1987         return nullptr;
1988       }
1989     }
1990 
1991     // Check elements
1992     RecTy *EltTy = nullptr;
1993     for (Init *V : Vals) {
1994       TypedInit *TArg = dyn_cast<TypedInit>(V);
1995       if (TArg) {
1996         if (EltTy) {
1997           EltTy = resolveTypes(EltTy, TArg->getType());
1998           if (!EltTy) {
1999             TokError("Incompatible types in list elements");
2000             return nullptr;
2001           }
2002         } else {
2003           EltTy = TArg->getType();
2004         }
2005       }
2006     }
2007 
2008     if (GivenEltTy) {
2009       if (EltTy) {
2010         // Verify consistency
2011         if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
2012           TokError("Incompatible types in list elements");
2013           return nullptr;
2014         }
2015       }
2016       EltTy = GivenEltTy;
2017     }
2018 
2019     if (!EltTy) {
2020       if (!ItemType) {
2021         TokError("No type for list");
2022         return nullptr;
2023       }
2024       DeducedEltTy = GivenListTy->getElementType();
2025     } else {
2026       // Make sure the deduced type is compatible with the given type
2027       if (GivenListTy) {
2028         if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
2029           TokError(Twine("Element type mismatch for list: element type '") +
2030                    EltTy->getAsString() + "' not convertible to '" +
2031                    GivenListTy->getElementType()->getAsString());
2032           return nullptr;
2033         }
2034       }
2035       DeducedEltTy = EltTy;
2036     }
2037 
2038     return ListInit::get(Vals, DeducedEltTy);
2039   }
2040   case tgtok::l_paren: {         // Value ::= '(' IDValue DagArgList ')'
2041     Lex.Lex();   // eat the '('
2042     if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast &&
2043         Lex.getCode() != tgtok::question && Lex.getCode() != tgtok::XGetOp) {
2044       TokError("expected identifier in dag init");
2045       return nullptr;
2046     }
2047 
2048     Init *Operator = ParseValue(CurRec);
2049     if (!Operator) return nullptr;
2050 
2051     // If the operator name is present, parse it.
2052     StringInit *OperatorName = nullptr;
2053     if (consume(tgtok::colon)) {
2054       if (Lex.getCode() != tgtok::VarName) { // eat the ':'
2055         TokError("expected variable name in dag operator");
2056         return nullptr;
2057       }
2058       OperatorName = StringInit::get(Lex.getCurStrVal());
2059       Lex.Lex();  // eat the VarName.
2060     }
2061 
2062     SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs;
2063     if (Lex.getCode() != tgtok::r_paren) {
2064       ParseDagArgList(DagArgs, CurRec);
2065       if (DagArgs.empty()) return nullptr;
2066     }
2067 
2068     if (!consume(tgtok::r_paren)) {
2069       TokError("expected ')' in dag init");
2070       return nullptr;
2071     }
2072 
2073     return DagInit::get(Operator, OperatorName, DagArgs);
2074   }
2075 
2076   case tgtok::XHead:
2077   case tgtok::XTail:
2078   case tgtok::XSize:
2079   case tgtok::XEmpty:
2080   case tgtok::XCast:
2081   case tgtok::XGetOp:  // Value ::= !unop '(' Value ')'
2082   case tgtok::XIsA:
2083   case tgtok::XConcat:
2084   case tgtok::XDag:
2085   case tgtok::XADD:
2086   case tgtok::XMUL:
2087   case tgtok::XAND:
2088   case tgtok::XOR:
2089   case tgtok::XSRA:
2090   case tgtok::XSRL:
2091   case tgtok::XSHL:
2092   case tgtok::XEq:
2093   case tgtok::XNe:
2094   case tgtok::XLe:
2095   case tgtok::XLt:
2096   case tgtok::XGe:
2097   case tgtok::XGt:
2098   case tgtok::XListConcat:
2099   case tgtok::XListSplat:
2100   case tgtok::XStrConcat:
2101   case tgtok::XSetOp:   // Value ::= !binop '(' Value ',' Value ')'
2102   case tgtok::XIf:
2103   case tgtok::XCond:
2104   case tgtok::XFoldl:
2105   case tgtok::XForEach:
2106   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
2107     return ParseOperation(CurRec, ItemType);
2108   }
2109   }
2110 
2111   return R;
2112 }
2113 
2114 /// ParseValue - Parse a tblgen value.  This returns null on error.
2115 ///
2116 ///   Value       ::= SimpleValue ValueSuffix*
2117 ///   ValueSuffix ::= '{' BitList '}'
2118 ///   ValueSuffix ::= '[' BitList ']'
2119 ///   ValueSuffix ::= '.' ID
2120 ///
2121 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
2122   Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
2123   if (!Result) return nullptr;
2124 
2125   // Parse the suffixes now if present.
2126   while (true) {
2127     switch (Lex.getCode()) {
2128     default: return Result;
2129     case tgtok::l_brace: {
2130       if (Mode == ParseNameMode)
2131         // This is the beginning of the object body.
2132         return Result;
2133 
2134       SMLoc CurlyLoc = Lex.getLoc();
2135       Lex.Lex(); // eat the '{'
2136       SmallVector<unsigned, 16> Ranges;
2137       ParseRangeList(Ranges);
2138       if (Ranges.empty()) return nullptr;
2139 
2140       // Reverse the bitlist.
2141       std::reverse(Ranges.begin(), Ranges.end());
2142       Result = Result->convertInitializerBitRange(Ranges);
2143       if (!Result) {
2144         Error(CurlyLoc, "Invalid bit range for value");
2145         return nullptr;
2146       }
2147 
2148       // Eat the '}'.
2149       if (!consume(tgtok::r_brace)) {
2150         TokError("expected '}' at end of bit range list");
2151         return nullptr;
2152       }
2153       break;
2154     }
2155     case tgtok::l_square: {
2156       SMLoc SquareLoc = Lex.getLoc();
2157       Lex.Lex(); // eat the '['
2158       SmallVector<unsigned, 16> Ranges;
2159       ParseRangeList(Ranges);
2160       if (Ranges.empty()) return nullptr;
2161 
2162       Result = Result->convertInitListSlice(Ranges);
2163       if (!Result) {
2164         Error(SquareLoc, "Invalid range for list slice");
2165         return nullptr;
2166       }
2167 
2168       // Eat the ']'.
2169       if (!consume(tgtok::r_square)) {
2170         TokError("expected ']' at end of list slice");
2171         return nullptr;
2172       }
2173       break;
2174     }
2175     case tgtok::dot: {
2176       if (Lex.Lex() != tgtok::Id) {  // eat the .
2177         TokError("expected field identifier after '.'");
2178         return nullptr;
2179       }
2180       StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2181       if (!Result->getFieldType(FieldName)) {
2182         TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
2183                  Result->getAsString() + "'");
2184         return nullptr;
2185       }
2186       Result = FieldInit::get(Result, FieldName)->Fold(CurRec);
2187       Lex.Lex();  // eat field name
2188       break;
2189     }
2190 
2191     case tgtok::paste:
2192       SMLoc PasteLoc = Lex.getLoc();
2193       TypedInit *LHS = dyn_cast<TypedInit>(Result);
2194       if (!LHS) {
2195         Error(PasteLoc, "LHS of paste is not typed!");
2196         return nullptr;
2197       }
2198 
2199       // Check if it's a 'listA # listB'
2200       if (isa<ListRecTy>(LHS->getType())) {
2201         Lex.Lex();  // Eat the '#'.
2202 
2203         switch (Lex.getCode()) {
2204         case tgtok::colon:
2205         case tgtok::semi:
2206         case tgtok::l_brace:
2207           Result = LHS; // trailing paste, ignore.
2208           break;
2209         default:
2210           Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
2211           if (!RHSResult)
2212             return nullptr;
2213           Result = BinOpInit::getListConcat(LHS, RHSResult);
2214         }
2215         break;
2216       }
2217 
2218       // Create a !strconcat() operation, first casting each operand to
2219       // a string if necessary.
2220       if (LHS->getType() != StringRecTy::get()) {
2221         auto CastLHS = dyn_cast<TypedInit>(
2222             UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get())
2223                 ->Fold(CurRec));
2224         if (!CastLHS) {
2225           Error(PasteLoc,
2226                 Twine("can't cast '") + LHS->getAsString() + "' to string");
2227           return nullptr;
2228         }
2229         LHS = CastLHS;
2230       }
2231 
2232       TypedInit *RHS = nullptr;
2233 
2234       Lex.Lex();  // Eat the '#'.
2235       switch (Lex.getCode()) {
2236       case tgtok::colon:
2237       case tgtok::semi:
2238       case tgtok::l_brace:
2239         // These are all of the tokens that can begin an object body.
2240         // Some of these can also begin values but we disallow those cases
2241         // because they are unlikely to be useful.
2242 
2243         // Trailing paste, concat with an empty string.
2244         RHS = StringInit::get("");
2245         break;
2246 
2247       default:
2248         Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode);
2249         if (!RHSResult)
2250           return nullptr;
2251         RHS = dyn_cast<TypedInit>(RHSResult);
2252         if (!RHS) {
2253           Error(PasteLoc, "RHS of paste is not typed!");
2254           return nullptr;
2255         }
2256 
2257         if (RHS->getType() != StringRecTy::get()) {
2258           auto CastRHS = dyn_cast<TypedInit>(
2259               UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get())
2260                   ->Fold(CurRec));
2261           if (!CastRHS) {
2262             Error(PasteLoc,
2263                   Twine("can't cast '") + RHS->getAsString() + "' to string");
2264             return nullptr;
2265           }
2266           RHS = CastRHS;
2267         }
2268 
2269         break;
2270       }
2271 
2272       Result = BinOpInit::getStrConcat(LHS, RHS);
2273       break;
2274     }
2275   }
2276 }
2277 
2278 /// ParseDagArgList - Parse the argument list for a dag literal expression.
2279 ///
2280 ///    DagArg     ::= Value (':' VARNAME)?
2281 ///    DagArg     ::= VARNAME
2282 ///    DagArgList ::= DagArg
2283 ///    DagArgList ::= DagArgList ',' DagArg
2284 void TGParser::ParseDagArgList(
2285     SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result,
2286     Record *CurRec) {
2287 
2288   while (true) {
2289     // DagArg ::= VARNAME
2290     if (Lex.getCode() == tgtok::VarName) {
2291       // A missing value is treated like '?'.
2292       StringInit *VarName = StringInit::get(Lex.getCurStrVal());
2293       Result.emplace_back(UnsetInit::get(), VarName);
2294       Lex.Lex();
2295     } else {
2296       // DagArg ::= Value (':' VARNAME)?
2297       Init *Val = ParseValue(CurRec);
2298       if (!Val) {
2299         Result.clear();
2300         return;
2301       }
2302 
2303       // If the variable name is present, add it.
2304       StringInit *VarName = nullptr;
2305       if (Lex.getCode() == tgtok::colon) {
2306         if (Lex.Lex() != tgtok::VarName) { // eat the ':'
2307           TokError("expected variable name in dag literal");
2308           Result.clear();
2309           return;
2310         }
2311         VarName = StringInit::get(Lex.getCurStrVal());
2312         Lex.Lex();  // eat the VarName.
2313       }
2314 
2315       Result.push_back(std::make_pair(Val, VarName));
2316     }
2317     if (!consume(tgtok::comma))
2318       break;
2319   }
2320 }
2321 
2322 /// ParseValueList - Parse a comma separated list of values, returning them as a
2323 /// vector.  Note that this always expects to be able to parse at least one
2324 /// value.  It returns an empty list if this is not possible.
2325 ///
2326 ///   ValueList ::= Value (',' Value)
2327 ///
2328 void TGParser::ParseValueList(SmallVectorImpl<Init*> &Result, Record *CurRec,
2329                               Record *ArgsRec, RecTy *EltTy) {
2330   RecTy *ItemType = EltTy;
2331   unsigned int ArgN = 0;
2332   if (ArgsRec && !EltTy) {
2333     ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2334     if (TArgs.empty()) {
2335       TokError("template argument provided to non-template class");
2336       Result.clear();
2337       return;
2338     }
2339     const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2340     if (!RV) {
2341       errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
2342         << ")\n";
2343     }
2344     assert(RV && "Template argument record not found??");
2345     ItemType = RV->getType();
2346     ++ArgN;
2347   }
2348   Result.push_back(ParseValue(CurRec, ItemType));
2349   if (!Result.back()) {
2350     Result.clear();
2351     return;
2352   }
2353 
2354   while (consume(tgtok::comma)) {
2355     // ignore trailing comma for lists
2356     if (Lex.getCode() == tgtok::r_square)
2357       return;
2358 
2359     if (ArgsRec && !EltTy) {
2360       ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2361       if (ArgN >= TArgs.size()) {
2362         TokError("too many template arguments");
2363         Result.clear();
2364         return;
2365       }
2366       const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2367       assert(RV && "Template argument record not found??");
2368       ItemType = RV->getType();
2369       ++ArgN;
2370     }
2371     Result.push_back(ParseValue(CurRec, ItemType));
2372     if (!Result.back()) {
2373       Result.clear();
2374       return;
2375     }
2376   }
2377 }
2378 
2379 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
2380 /// empty string on error.  This can happen in a number of different context's,
2381 /// including within a def or in the template args for a def (which which case
2382 /// CurRec will be non-null) and within the template args for a multiclass (in
2383 /// which case CurRec will be null, but CurMultiClass will be set).  This can
2384 /// also happen within a def that is within a multiclass, which will set both
2385 /// CurRec and CurMultiClass.
2386 ///
2387 ///  Declaration ::= FIELD? Type ID ('=' Value)?
2388 ///
2389 Init *TGParser::ParseDeclaration(Record *CurRec,
2390                                        bool ParsingTemplateArgs) {
2391   // Read the field prefix if present.
2392   bool HasField = consume(tgtok::Field);
2393 
2394   RecTy *Type = ParseType();
2395   if (!Type) return nullptr;
2396 
2397   if (Lex.getCode() != tgtok::Id) {
2398     TokError("Expected identifier in declaration");
2399     return nullptr;
2400   }
2401 
2402   std::string Str = Lex.getCurStrVal();
2403   if (Str == "NAME") {
2404     TokError("'" + Str + "' is a reserved variable name");
2405     return nullptr;
2406   }
2407 
2408   SMLoc IdLoc = Lex.getLoc();
2409   Init *DeclName = StringInit::get(Str);
2410   Lex.Lex();
2411 
2412   if (ParsingTemplateArgs) {
2413     if (CurRec)
2414       DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
2415     else
2416       assert(CurMultiClass);
2417     if (CurMultiClass)
2418       DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
2419                              "::");
2420   }
2421 
2422   // Add the value.
2423   if (AddValue(CurRec, IdLoc, RecordVal(DeclName, IdLoc, Type, HasField)))
2424     return nullptr;
2425 
2426   // If a value is present, parse it.
2427   if (consume(tgtok::equal)) {
2428     SMLoc ValLoc = Lex.getLoc();
2429     Init *Val = ParseValue(CurRec, Type);
2430     if (!Val ||
2431         SetValue(CurRec, ValLoc, DeclName, None, Val))
2432       // Return the name, even if an error is thrown.  This is so that we can
2433       // continue to make some progress, even without the value having been
2434       // initialized.
2435       return DeclName;
2436   }
2437 
2438   return DeclName;
2439 }
2440 
2441 /// ParseForeachDeclaration - Read a foreach declaration, returning
2442 /// the name of the declared object or a NULL Init on error.  Return
2443 /// the name of the parsed initializer list through ForeachListName.
2444 ///
2445 ///  ForeachDeclaration ::= ID '=' '{' RangeList '}'
2446 ///  ForeachDeclaration ::= ID '=' RangePiece
2447 ///  ForeachDeclaration ::= ID '=' Value
2448 ///
2449 VarInit *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) {
2450   if (Lex.getCode() != tgtok::Id) {
2451     TokError("Expected identifier in foreach declaration");
2452     return nullptr;
2453   }
2454 
2455   Init *DeclName = StringInit::get(Lex.getCurStrVal());
2456   Lex.Lex();
2457 
2458   // If a value is present, parse it.
2459   if (!consume(tgtok::equal)) {
2460     TokError("Expected '=' in foreach declaration");
2461     return nullptr;
2462   }
2463 
2464   RecTy *IterType = nullptr;
2465   SmallVector<unsigned, 16> Ranges;
2466 
2467   switch (Lex.getCode()) {
2468   case tgtok::l_brace: { // '{' RangeList '}'
2469     Lex.Lex(); // eat the '{'
2470     ParseRangeList(Ranges);
2471     if (!consume(tgtok::r_brace)) {
2472       TokError("expected '}' at end of bit range list");
2473       return nullptr;
2474     }
2475     break;
2476   }
2477 
2478   default: {
2479     SMLoc ValueLoc = Lex.getLoc();
2480     Init *I = ParseValue(nullptr);
2481     if (!I)
2482       return nullptr;
2483 
2484     TypedInit *TI = dyn_cast<TypedInit>(I);
2485     if (TI && isa<ListRecTy>(TI->getType())) {
2486       ForeachListValue = I;
2487       IterType = cast<ListRecTy>(TI->getType())->getElementType();
2488       break;
2489     }
2490 
2491     if (TI) {
2492       if (ParseRangePiece(Ranges, TI))
2493         return nullptr;
2494       break;
2495     }
2496 
2497     std::string Type;
2498     if (TI)
2499       Type = (Twine("' of type '") + TI->getType()->getAsString()).str();
2500     Error(ValueLoc, "expected a list, got '" + I->getAsString() + Type + "'");
2501     if (CurMultiClass) {
2502       PrintNote({}, "references to multiclass template arguments cannot be "
2503                 "resolved at this time");
2504     }
2505     return nullptr;
2506   }
2507   }
2508 
2509 
2510   if (!Ranges.empty()) {
2511     assert(!IterType && "Type already initialized?");
2512     IterType = IntRecTy::get();
2513     std::vector<Init*> Values;
2514     for (unsigned R : Ranges)
2515       Values.push_back(IntInit::get(R));
2516     ForeachListValue = ListInit::get(Values, IterType);
2517   }
2518 
2519   if (!IterType)
2520     return nullptr;
2521 
2522   return VarInit::get(DeclName, IterType);
2523 }
2524 
2525 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
2526 /// sequence of template-declarations in <>'s.  If CurRec is non-null, these are
2527 /// template args for a def, which may or may not be in a multiclass.  If null,
2528 /// these are the template args for a multiclass.
2529 ///
2530 ///    TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
2531 ///
2532 bool TGParser::ParseTemplateArgList(Record *CurRec) {
2533   assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
2534   Lex.Lex(); // eat the '<'
2535 
2536   Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
2537 
2538   // Read the first declaration.
2539   Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2540   if (!TemplArg)
2541     return true;
2542 
2543   TheRecToAddTo->addTemplateArg(TemplArg);
2544 
2545   while (consume(tgtok::comma)) {
2546     // Read the following declarations.
2547     SMLoc Loc = Lex.getLoc();
2548     TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2549     if (!TemplArg)
2550       return true;
2551 
2552     if (TheRecToAddTo->isTemplateArg(TemplArg))
2553       return Error(Loc, "template argument with the same name has already been "
2554                         "defined");
2555 
2556     TheRecToAddTo->addTemplateArg(TemplArg);
2557   }
2558 
2559   if (!consume(tgtok::greater))
2560     return TokError("expected '>' at end of template argument list");
2561   return false;
2562 }
2563 
2564 /// ParseBodyItem - Parse a single item at within the body of a def or class.
2565 ///
2566 ///   BodyItem ::= Declaration ';'
2567 ///   BodyItem ::= LET ID OptionalBitList '=' Value ';'
2568 ///   BodyItem ::= Defvar
2569 bool TGParser::ParseBodyItem(Record *CurRec) {
2570   if (Lex.getCode() == tgtok::Defvar)
2571     return ParseDefvar();
2572 
2573   if (Lex.getCode() != tgtok::Let) {
2574     if (!ParseDeclaration(CurRec, false))
2575       return true;
2576 
2577     if (!consume(tgtok::semi))
2578       return TokError("expected ';' after declaration");
2579     return false;
2580   }
2581 
2582   // LET ID OptionalRangeList '=' Value ';'
2583   if (Lex.Lex() != tgtok::Id)
2584     return TokError("expected field identifier after let");
2585 
2586   SMLoc IdLoc = Lex.getLoc();
2587   StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2588   Lex.Lex();  // eat the field name.
2589 
2590   SmallVector<unsigned, 16> BitList;
2591   if (ParseOptionalBitList(BitList))
2592     return true;
2593   std::reverse(BitList.begin(), BitList.end());
2594 
2595   if (!consume(tgtok::equal))
2596     return TokError("expected '=' in let expression");
2597 
2598   RecordVal *Field = CurRec->getValue(FieldName);
2599   if (!Field)
2600     return TokError("Value '" + FieldName->getValue() + "' unknown!");
2601 
2602   RecTy *Type = Field->getType();
2603   if (!BitList.empty() && isa<BitsRecTy>(Type)) {
2604     // When assigning to a subset of a 'bits' object, expect the RHS to have
2605     // the type of that subset instead of the type of the whole object.
2606     Type = BitsRecTy::get(BitList.size());
2607   }
2608 
2609   Init *Val = ParseValue(CurRec, Type);
2610   if (!Val) return true;
2611 
2612   if (!consume(tgtok::semi))
2613     return TokError("expected ';' after let expression");
2614 
2615   return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
2616 }
2617 
2618 /// ParseBody - Read the body of a class or def.  Return true on error, false on
2619 /// success.
2620 ///
2621 ///   Body     ::= ';'
2622 ///   Body     ::= '{' BodyList '}'
2623 ///   BodyList BodyItem*
2624 ///
2625 bool TGParser::ParseBody(Record *CurRec) {
2626   // If this is a null definition, just eat the semi and return.
2627   if (consume(tgtok::semi))
2628     return false;
2629 
2630   if (!consume(tgtok::l_brace))
2631     return TokError("Expected ';' or '{' to start body");
2632 
2633   // An object body introduces a new scope for local variables.
2634   TGLocalVarScope *BodyScope = PushLocalScope();
2635 
2636   while (Lex.getCode() != tgtok::r_brace)
2637     if (ParseBodyItem(CurRec))
2638       return true;
2639 
2640   PopLocalScope(BodyScope);
2641 
2642   // Eat the '}'.
2643   Lex.Lex();
2644   return false;
2645 }
2646 
2647 /// Apply the current let bindings to \a CurRec.
2648 /// \returns true on error, false otherwise.
2649 bool TGParser::ApplyLetStack(Record *CurRec) {
2650   for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
2651     for (LetRecord &LR : LetInfo)
2652       if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
2653         return true;
2654   return false;
2655 }
2656 
2657 bool TGParser::ApplyLetStack(RecordsEntry &Entry) {
2658   if (Entry.Rec)
2659     return ApplyLetStack(Entry.Rec.get());
2660 
2661   for (auto &E : Entry.Loop->Entries) {
2662     if (ApplyLetStack(E))
2663       return true;
2664   }
2665 
2666   return false;
2667 }
2668 
2669 /// ParseObjectBody - Parse the body of a def or class.  This consists of an
2670 /// optional ClassList followed by a Body.  CurRec is the current def or class
2671 /// that is being parsed.
2672 ///
2673 ///   ObjectBody      ::= BaseClassList Body
2674 ///   BaseClassList   ::= /*empty*/
2675 ///   BaseClassList   ::= ':' BaseClassListNE
2676 ///   BaseClassListNE ::= SubClassRef (',' SubClassRef)*
2677 ///
2678 bool TGParser::ParseObjectBody(Record *CurRec) {
2679   // If there is a baseclass list, read it.
2680   if (consume(tgtok::colon)) {
2681 
2682     // Read all of the subclasses.
2683     SubClassReference SubClass = ParseSubClassReference(CurRec, false);
2684     while (true) {
2685       // Check for error.
2686       if (!SubClass.Rec) return true;
2687 
2688       // Add it.
2689       if (AddSubClass(CurRec, SubClass))
2690         return true;
2691 
2692       if (!consume(tgtok::comma))
2693         break;
2694       SubClass = ParseSubClassReference(CurRec, false);
2695     }
2696   }
2697 
2698   if (ApplyLetStack(CurRec))
2699     return true;
2700 
2701   return ParseBody(CurRec);
2702 }
2703 
2704 /// ParseDef - Parse and return a top level or multiclass def, return the record
2705 /// corresponding to it.  This returns null on error.
2706 ///
2707 ///   DefInst ::= DEF ObjectName ObjectBody
2708 ///
2709 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2710   SMLoc DefLoc = Lex.getLoc();
2711   assert(Lex.getCode() == tgtok::Def && "Unknown tok");
2712   Lex.Lex();  // Eat the 'def' token.
2713 
2714   // Parse ObjectName and make a record for it.
2715   std::unique_ptr<Record> CurRec;
2716   Init *Name = ParseObjectName(CurMultiClass);
2717   if (!Name)
2718     return true;
2719 
2720   if (isa<UnsetInit>(Name))
2721     CurRec = std::make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records,
2722                                  /*Anonymous=*/true);
2723   else
2724     CurRec = std::make_unique<Record>(Name, DefLoc, Records);
2725 
2726   if (ParseObjectBody(CurRec.get()))
2727     return true;
2728 
2729   return addEntry(std::move(CurRec));
2730 }
2731 
2732 /// ParseDefset - Parse a defset statement.
2733 ///
2734 ///   Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
2735 ///
2736 bool TGParser::ParseDefset() {
2737   assert(Lex.getCode() == tgtok::Defset);
2738   Lex.Lex(); // Eat the 'defset' token
2739 
2740   DefsetRecord Defset;
2741   Defset.Loc = Lex.getLoc();
2742   RecTy *Type = ParseType();
2743   if (!Type)
2744     return true;
2745   if (!isa<ListRecTy>(Type))
2746     return Error(Defset.Loc, "expected list type");
2747   Defset.EltTy = cast<ListRecTy>(Type)->getElementType();
2748 
2749   if (Lex.getCode() != tgtok::Id)
2750     return TokError("expected identifier");
2751   StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
2752   if (Records.getGlobal(DeclName->getValue()))
2753     return TokError("def or global variable of this name already exists");
2754 
2755   if (Lex.Lex() != tgtok::equal) // Eat the identifier
2756     return TokError("expected '='");
2757   if (Lex.Lex() != tgtok::l_brace) // Eat the '='
2758     return TokError("expected '{'");
2759   SMLoc BraceLoc = Lex.getLoc();
2760   Lex.Lex(); // Eat the '{'
2761 
2762   Defsets.push_back(&Defset);
2763   bool Err = ParseObjectList(nullptr);
2764   Defsets.pop_back();
2765   if (Err)
2766     return true;
2767 
2768   if (!consume(tgtok::r_brace)) {
2769     TokError("expected '}' at end of defset");
2770     return Error(BraceLoc, "to match this '{'");
2771   }
2772 
2773   Records.addExtraGlobal(DeclName->getValue(),
2774                          ListInit::get(Defset.Elements, Defset.EltTy));
2775   return false;
2776 }
2777 
2778 /// ParseDefvar - Parse a defvar statement.
2779 ///
2780 ///   Defvar ::= DEFVAR Id '=' Value ';'
2781 ///
2782 bool TGParser::ParseDefvar() {
2783   assert(Lex.getCode() == tgtok::Defvar);
2784   Lex.Lex(); // Eat the 'defvar' token
2785 
2786   if (Lex.getCode() != tgtok::Id)
2787     return TokError("expected identifier");
2788   StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
2789   if (CurLocalScope) {
2790     if (CurLocalScope->varAlreadyDefined(DeclName->getValue()))
2791       return TokError("local variable of this name already exists");
2792   } else {
2793     if (Records.getGlobal(DeclName->getValue()))
2794       return TokError("def or global variable of this name already exists");
2795   }
2796 
2797   Lex.Lex();
2798   if (!consume(tgtok::equal))
2799     return TokError("expected '='");
2800 
2801   Init *Value = ParseValue(nullptr);
2802   if (!Value)
2803     return true;
2804 
2805   if (!consume(tgtok::semi))
2806     return TokError("expected ';'");
2807 
2808   if (CurLocalScope)
2809     CurLocalScope->addVar(DeclName->getValue(), Value);
2810   else
2811     Records.addExtraGlobal(DeclName->getValue(), Value);
2812 
2813   return false;
2814 }
2815 
2816 /// ParseForeach - Parse a for statement.  Return the record corresponding
2817 /// to it.  This returns true on error.
2818 ///
2819 ///   Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2820 ///   Foreach ::= FOREACH Declaration IN Object
2821 ///
2822 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2823   SMLoc Loc = Lex.getLoc();
2824   assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2825   Lex.Lex();  // Eat the 'for' token.
2826 
2827   // Make a temporary object to record items associated with the for
2828   // loop.
2829   Init *ListValue = nullptr;
2830   VarInit *IterName = ParseForeachDeclaration(ListValue);
2831   if (!IterName)
2832     return TokError("expected declaration in for");
2833 
2834   if (!consume(tgtok::In))
2835     return TokError("Unknown tok");
2836 
2837   // Create a loop object and remember it.
2838   Loops.push_back(std::make_unique<ForeachLoop>(Loc, IterName, ListValue));
2839 
2840   // A foreach loop introduces a new scope for local variables.
2841   TGLocalVarScope *ForeachScope = PushLocalScope();
2842 
2843   if (Lex.getCode() != tgtok::l_brace) {
2844     // FOREACH Declaration IN Object
2845     if (ParseObject(CurMultiClass))
2846       return true;
2847   } else {
2848     SMLoc BraceLoc = Lex.getLoc();
2849     // Otherwise, this is a group foreach.
2850     Lex.Lex();  // eat the '{'.
2851 
2852     // Parse the object list.
2853     if (ParseObjectList(CurMultiClass))
2854       return true;
2855 
2856     if (!consume(tgtok::r_brace)) {
2857       TokError("expected '}' at end of foreach command");
2858       return Error(BraceLoc, "to match this '{'");
2859     }
2860   }
2861 
2862   PopLocalScope(ForeachScope);
2863 
2864   // Resolve the loop or store it for later resolution.
2865   std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
2866   Loops.pop_back();
2867 
2868   return addEntry(std::move(Loop));
2869 }
2870 
2871 /// ParseIf - Parse an if statement.
2872 ///
2873 ///   If ::= IF Value THEN IfBody
2874 ///   If ::= IF Value THEN IfBody ELSE IfBody
2875 ///
2876 bool TGParser::ParseIf(MultiClass *CurMultiClass) {
2877   SMLoc Loc = Lex.getLoc();
2878   assert(Lex.getCode() == tgtok::If && "Unknown tok");
2879   Lex.Lex(); // Eat the 'if' token.
2880 
2881   // Make a temporary object to record items associated with the for
2882   // loop.
2883   Init *Condition = ParseValue(nullptr);
2884   if (!Condition)
2885     return true;
2886 
2887   if (!consume(tgtok::Then))
2888     return TokError("Unknown tok");
2889 
2890   // We have to be able to save if statements to execute later, and they have
2891   // to live on the same stack as foreach loops. The simplest implementation
2892   // technique is to convert each 'then' or 'else' clause *into* a foreach
2893   // loop, over a list of length 0 or 1 depending on the condition, and with no
2894   // iteration variable being assigned.
2895 
2896   ListInit *EmptyList = ListInit::get({}, BitRecTy::get());
2897   ListInit *SingletonList = ListInit::get({BitInit::get(1)}, BitRecTy::get());
2898   RecTy *BitListTy = ListRecTy::get(BitRecTy::get());
2899 
2900   // The foreach containing the then-clause selects SingletonList if
2901   // the condition is true.
2902   Init *ThenClauseList =
2903       TernOpInit::get(TernOpInit::IF, Condition, SingletonList, EmptyList,
2904                       BitListTy)
2905           ->Fold(nullptr);
2906   Loops.push_back(std::make_unique<ForeachLoop>(Loc, nullptr, ThenClauseList));
2907 
2908   if (ParseIfBody(CurMultiClass, "then"))
2909     return true;
2910 
2911   std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
2912   Loops.pop_back();
2913 
2914   if (addEntry(std::move(Loop)))
2915     return true;
2916 
2917   // Now look for an optional else clause. The if-else syntax has the usual
2918   // dangling-else ambiguity, and by greedily matching an else here if we can,
2919   // we implement the usual resolution of pairing with the innermost unmatched
2920   // if.
2921   if (consume(tgtok::ElseKW)) {
2922     // The foreach containing the else-clause uses the same pair of lists as
2923     // above, but this time, selects SingletonList if the condition is *false*.
2924     Init *ElseClauseList =
2925         TernOpInit::get(TernOpInit::IF, Condition, EmptyList, SingletonList,
2926                         BitListTy)
2927             ->Fold(nullptr);
2928     Loops.push_back(
2929         std::make_unique<ForeachLoop>(Loc, nullptr, ElseClauseList));
2930 
2931     if (ParseIfBody(CurMultiClass, "else"))
2932       return true;
2933 
2934     Loop = std::move(Loops.back());
2935     Loops.pop_back();
2936 
2937     if (addEntry(std::move(Loop)))
2938       return true;
2939   }
2940 
2941   return false;
2942 }
2943 
2944 /// ParseIfBody - Parse the then-clause or else-clause of an if statement.
2945 ///
2946 ///   IfBody ::= Object
2947 ///   IfBody ::= '{' ObjectList '}'
2948 ///
2949 bool TGParser::ParseIfBody(MultiClass *CurMultiClass, StringRef Kind) {
2950   TGLocalVarScope *BodyScope = PushLocalScope();
2951 
2952   if (Lex.getCode() != tgtok::l_brace) {
2953     // A single object.
2954     if (ParseObject(CurMultiClass))
2955       return true;
2956   } else {
2957     SMLoc BraceLoc = Lex.getLoc();
2958     // A braced block.
2959     Lex.Lex(); // eat the '{'.
2960 
2961     // Parse the object list.
2962     if (ParseObjectList(CurMultiClass))
2963       return true;
2964 
2965     if (!consume(tgtok::r_brace)) {
2966       TokError("expected '}' at end of '" + Kind + "' clause");
2967       return Error(BraceLoc, "to match this '{'");
2968     }
2969   }
2970 
2971   PopLocalScope(BodyScope);
2972   return false;
2973 }
2974 
2975 /// ParseClass - Parse a tblgen class definition.
2976 ///
2977 ///   ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2978 ///
2979 bool TGParser::ParseClass() {
2980   assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2981   Lex.Lex();
2982 
2983   if (Lex.getCode() != tgtok::Id)
2984     return TokError("expected class name after 'class' keyword");
2985 
2986   Record *CurRec = Records.getClass(Lex.getCurStrVal());
2987   if (CurRec) {
2988     // If the body was previously defined, this is an error.
2989     if (!CurRec->getValues().empty() ||
2990         !CurRec->getSuperClasses().empty() ||
2991         !CurRec->getTemplateArgs().empty())
2992       return TokError("Class '" + CurRec->getNameInitAsString() +
2993                       "' already defined");
2994   } else {
2995     // If this is the first reference to this class, create and add it.
2996     auto NewRec =
2997         std::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records,
2998                                   /*Class=*/true);
2999     CurRec = NewRec.get();
3000     Records.addClass(std::move(NewRec));
3001   }
3002   Lex.Lex(); // eat the name.
3003 
3004   // If there are template args, parse them.
3005   if (Lex.getCode() == tgtok::less)
3006     if (ParseTemplateArgList(CurRec))
3007       return true;
3008 
3009   return ParseObjectBody(CurRec);
3010 }
3011 
3012 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
3013 /// of LetRecords.
3014 ///
3015 ///   LetList ::= LetItem (',' LetItem)*
3016 ///   LetItem ::= ID OptionalRangeList '=' Value
3017 ///
3018 void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) {
3019   do {
3020     if (Lex.getCode() != tgtok::Id) {
3021       TokError("expected identifier in let definition");
3022       Result.clear();
3023       return;
3024     }
3025 
3026     StringInit *Name = StringInit::get(Lex.getCurStrVal());
3027     SMLoc NameLoc = Lex.getLoc();
3028     Lex.Lex();  // Eat the identifier.
3029 
3030     // Check for an optional RangeList.
3031     SmallVector<unsigned, 16> Bits;
3032     if (ParseOptionalRangeList(Bits)) {
3033       Result.clear();
3034       return;
3035     }
3036     std::reverse(Bits.begin(), Bits.end());
3037 
3038     if (!consume(tgtok::equal)) {
3039       TokError("expected '=' in let expression");
3040       Result.clear();
3041       return;
3042     }
3043 
3044     Init *Val = ParseValue(nullptr);
3045     if (!Val) {
3046       Result.clear();
3047       return;
3048     }
3049 
3050     // Now that we have everything, add the record.
3051     Result.emplace_back(Name, Bits, Val, NameLoc);
3052   } while (consume(tgtok::comma));
3053 }
3054 
3055 /// ParseTopLevelLet - Parse a 'let' at top level.  This can be a couple of
3056 /// different related productions. This works inside multiclasses too.
3057 ///
3058 ///   Object ::= LET LetList IN '{' ObjectList '}'
3059 ///   Object ::= LET LetList IN Object
3060 ///
3061 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
3062   assert(Lex.getCode() == tgtok::Let && "Unexpected token");
3063   Lex.Lex();
3064 
3065   // Add this entry to the let stack.
3066   SmallVector<LetRecord, 8> LetInfo;
3067   ParseLetList(LetInfo);
3068   if (LetInfo.empty()) return true;
3069   LetStack.push_back(std::move(LetInfo));
3070 
3071   if (!consume(tgtok::In))
3072     return TokError("expected 'in' at end of top-level 'let'");
3073 
3074   TGLocalVarScope *LetScope = PushLocalScope();
3075 
3076   // If this is a scalar let, just handle it now
3077   if (Lex.getCode() != tgtok::l_brace) {
3078     // LET LetList IN Object
3079     if (ParseObject(CurMultiClass))
3080       return true;
3081   } else {   // Object ::= LETCommand '{' ObjectList '}'
3082     SMLoc BraceLoc = Lex.getLoc();
3083     // Otherwise, this is a group let.
3084     Lex.Lex();  // eat the '{'.
3085 
3086     // Parse the object list.
3087     if (ParseObjectList(CurMultiClass))
3088       return true;
3089 
3090     if (!consume(tgtok::r_brace)) {
3091       TokError("expected '}' at end of top level let command");
3092       return Error(BraceLoc, "to match this '{'");
3093     }
3094   }
3095 
3096   PopLocalScope(LetScope);
3097 
3098   // Outside this let scope, this let block is not active.
3099   LetStack.pop_back();
3100   return false;
3101 }
3102 
3103 /// ParseMultiClass - Parse a multiclass definition.
3104 ///
3105 ///  MultiClassInst ::= MULTICLASS ID TemplateArgList?
3106 ///                     ':' BaseMultiClassList '{' MultiClassObject+ '}'
3107 ///  MultiClassObject ::= DefInst
3108 ///  MultiClassObject ::= MultiClassInst
3109 ///  MultiClassObject ::= DefMInst
3110 ///  MultiClassObject ::= LETCommand '{' ObjectList '}'
3111 ///  MultiClassObject ::= LETCommand Object
3112 ///
3113 bool TGParser::ParseMultiClass() {
3114   assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
3115   Lex.Lex();  // Eat the multiclass token.
3116 
3117   if (Lex.getCode() != tgtok::Id)
3118     return TokError("expected identifier after multiclass for name");
3119   std::string Name = Lex.getCurStrVal();
3120 
3121   auto Result =
3122     MultiClasses.insert(std::make_pair(Name,
3123                     std::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
3124 
3125   if (!Result.second)
3126     return TokError("multiclass '" + Name + "' already defined");
3127 
3128   CurMultiClass = Result.first->second.get();
3129   Lex.Lex();  // Eat the identifier.
3130 
3131   // If there are template args, parse them.
3132   if (Lex.getCode() == tgtok::less)
3133     if (ParseTemplateArgList(nullptr))
3134       return true;
3135 
3136   bool inherits = false;
3137 
3138   // If there are submulticlasses, parse them.
3139   if (consume(tgtok::colon)) {
3140     inherits = true;
3141 
3142     // Read all of the submulticlasses.
3143     SubMultiClassReference SubMultiClass =
3144       ParseSubMultiClassReference(CurMultiClass);
3145     while (true) {
3146       // Check for error.
3147       if (!SubMultiClass.MC) return true;
3148 
3149       // Add it.
3150       if (AddSubMultiClass(CurMultiClass, SubMultiClass))
3151         return true;
3152 
3153       if (!consume(tgtok::comma))
3154         break;
3155       SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
3156     }
3157   }
3158 
3159   if (Lex.getCode() != tgtok::l_brace) {
3160     if (!inherits)
3161       return TokError("expected '{' in multiclass definition");
3162     if (!consume(tgtok::semi))
3163       return TokError("expected ';' in multiclass definition");
3164   } else {
3165     if (Lex.Lex() == tgtok::r_brace)  // eat the '{'.
3166       return TokError("multiclass must contain at least one def");
3167 
3168     // A multiclass body introduces a new scope for local variables.
3169     TGLocalVarScope *MulticlassScope = PushLocalScope();
3170 
3171     while (Lex.getCode() != tgtok::r_brace) {
3172       switch (Lex.getCode()) {
3173       default:
3174         return TokError("expected 'let', 'def', 'defm', 'defvar', 'foreach' "
3175                         "or 'if' in multiclass body");
3176       case tgtok::Let:
3177       case tgtok::Def:
3178       case tgtok::Defm:
3179       case tgtok::Defvar:
3180       case tgtok::Foreach:
3181       case tgtok::If:
3182         if (ParseObject(CurMultiClass))
3183           return true;
3184         break;
3185       }
3186     }
3187     Lex.Lex();  // eat the '}'.
3188 
3189     PopLocalScope(MulticlassScope);
3190   }
3191 
3192   CurMultiClass = nullptr;
3193   return false;
3194 }
3195 
3196 /// ParseDefm - Parse the instantiation of a multiclass.
3197 ///
3198 ///   DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
3199 ///
3200 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
3201   assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
3202   Lex.Lex(); // eat the defm
3203 
3204   Init *DefmName = ParseObjectName(CurMultiClass);
3205   if (!DefmName)
3206     return true;
3207   if (isa<UnsetInit>(DefmName)) {
3208     DefmName = Records.getNewAnonymousName();
3209     if (CurMultiClass)
3210       DefmName = BinOpInit::getStrConcat(
3211           VarInit::get(QualifiedNameOfImplicitName(CurMultiClass),
3212                        StringRecTy::get()),
3213           DefmName);
3214   }
3215 
3216   if (Lex.getCode() != tgtok::colon)
3217     return TokError("expected ':' after defm identifier");
3218 
3219   // Keep track of the new generated record definitions.
3220   std::vector<RecordsEntry> NewEntries;
3221 
3222   // This record also inherits from a regular class (non-multiclass)?
3223   bool InheritFromClass = false;
3224 
3225   // eat the colon.
3226   Lex.Lex();
3227 
3228   SMLoc SubClassLoc = Lex.getLoc();
3229   SubClassReference Ref = ParseSubClassReference(nullptr, true);
3230 
3231   while (true) {
3232     if (!Ref.Rec) return true;
3233 
3234     // To instantiate a multiclass, we need to first get the multiclass, then
3235     // instantiate each def contained in the multiclass with the SubClassRef
3236     // template parameters.
3237     MultiClass *MC = MultiClasses[std::string(Ref.Rec->getName())].get();
3238     assert(MC && "Didn't lookup multiclass correctly?");
3239     ArrayRef<Init*> TemplateVals = Ref.TemplateArgs;
3240 
3241     // Verify that the correct number of template arguments were specified.
3242     ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs();
3243     if (TArgs.size() < TemplateVals.size())
3244       return Error(SubClassLoc,
3245                    "more template args specified than multiclass expects");
3246 
3247     SubstStack Substs;
3248     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
3249       if (i < TemplateVals.size()) {
3250         Substs.emplace_back(TArgs[i], TemplateVals[i]);
3251       } else {
3252         Init *Default = MC->Rec.getValue(TArgs[i])->getValue();
3253         if (!Default->isComplete()) {
3254           return Error(SubClassLoc,
3255                        "value not specified for template argument #" +
3256                            Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
3257                            ") of multiclass '" + MC->Rec.getNameInitAsString() +
3258                            "'");
3259         }
3260         Substs.emplace_back(TArgs[i], Default);
3261       }
3262     }
3263 
3264     Substs.emplace_back(QualifiedNameOfImplicitName(MC), DefmName);
3265 
3266     if (resolve(MC->Entries, Substs, CurMultiClass == nullptr, &NewEntries,
3267                 &SubClassLoc))
3268       return true;
3269 
3270     if (!consume(tgtok::comma))
3271       break;
3272 
3273     if (Lex.getCode() != tgtok::Id)
3274       return TokError("expected identifier");
3275 
3276     SubClassLoc = Lex.getLoc();
3277 
3278     // A defm can inherit from regular classes (non-multiclass) as
3279     // long as they come in the end of the inheritance list.
3280     InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
3281 
3282     if (InheritFromClass)
3283       break;
3284 
3285     Ref = ParseSubClassReference(nullptr, true);
3286   }
3287 
3288   if (InheritFromClass) {
3289     // Process all the classes to inherit as if they were part of a
3290     // regular 'def' and inherit all record values.
3291     SubClassReference SubClass = ParseSubClassReference(nullptr, false);
3292     while (true) {
3293       // Check for error.
3294       if (!SubClass.Rec) return true;
3295 
3296       // Get the expanded definition prototypes and teach them about
3297       // the record values the current class to inherit has
3298       for (auto &E : NewEntries) {
3299         // Add it.
3300         if (AddSubClass(E, SubClass))
3301           return true;
3302       }
3303 
3304       if (!consume(tgtok::comma))
3305         break;
3306       SubClass = ParseSubClassReference(nullptr, false);
3307     }
3308   }
3309 
3310   for (auto &E : NewEntries) {
3311     if (ApplyLetStack(E))
3312       return true;
3313 
3314     addEntry(std::move(E));
3315   }
3316 
3317   if (!consume(tgtok::semi))
3318     return TokError("expected ';' at end of defm");
3319 
3320   return false;
3321 }
3322 
3323 /// ParseObject
3324 ///   Object ::= ClassInst
3325 ///   Object ::= DefInst
3326 ///   Object ::= MultiClassInst
3327 ///   Object ::= DefMInst
3328 ///   Object ::= LETCommand '{' ObjectList '}'
3329 ///   Object ::= LETCommand Object
3330 ///   Object ::= Defset
3331 ///   Object ::= Defvar
3332 bool TGParser::ParseObject(MultiClass *MC) {
3333   switch (Lex.getCode()) {
3334   default:
3335     return TokError("Expected class, def, defm, defset, multiclass, let, "
3336                     "foreach or if");
3337   case tgtok::Let:   return ParseTopLevelLet(MC);
3338   case tgtok::Def:   return ParseDef(MC);
3339   case tgtok::Foreach:   return ParseForeach(MC);
3340   case tgtok::If:    return ParseIf(MC);
3341   case tgtok::Defm:  return ParseDefm(MC);
3342   case tgtok::Defset:
3343     if (MC)
3344       return TokError("defset is not allowed inside multiclass");
3345     return ParseDefset();
3346   case tgtok::Defvar:
3347     return ParseDefvar();
3348   case tgtok::Class:
3349     if (MC)
3350       return TokError("class is not allowed inside multiclass");
3351     if (!Loops.empty())
3352       return TokError("class is not allowed inside foreach loop");
3353     return ParseClass();
3354   case tgtok::MultiClass:
3355     if (!Loops.empty())
3356       return TokError("multiclass is not allowed inside foreach loop");
3357     return ParseMultiClass();
3358   }
3359 }
3360 
3361 /// ParseObjectList
3362 ///   ObjectList :== Object*
3363 bool TGParser::ParseObjectList(MultiClass *MC) {
3364   while (isObjectStart(Lex.getCode())) {
3365     if (ParseObject(MC))
3366       return true;
3367   }
3368   return false;
3369 }
3370 
3371 bool TGParser::ParseFile() {
3372   Lex.Lex(); // Prime the lexer.
3373   if (ParseObjectList()) return true;
3374 
3375   // If we have unread input at the end of the file, report it.
3376   if (Lex.getCode() == tgtok::Eof)
3377     return false;
3378 
3379   return TokError("Unexpected input at top level");
3380 }
3381 
3382 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3383 LLVM_DUMP_METHOD void RecordsEntry::dump() const {
3384   if (Loop)
3385     Loop->dump();
3386   if (Rec)
3387     Rec->dump();
3388 }
3389 
3390 LLVM_DUMP_METHOD void ForeachLoop::dump() const {
3391   errs() << "foreach " << IterVar->getAsString() << " = "
3392          << ListValue->getAsString() << " in {\n";
3393 
3394   for (const auto &E : Entries)
3395     E.dump();
3396 
3397   errs() << "}\n";
3398 }
3399 
3400 LLVM_DUMP_METHOD void MultiClass::dump() const {
3401   errs() << "Record:\n";
3402   Rec.dump();
3403 
3404   errs() << "Defs:\n";
3405   for (const auto &E : Entries)
3406     E.dump();
3407 }
3408 #endif
3409