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 bang operator");
910     return nullptr;
911   case tgtok::XNOT:
912   case tgtok::XHead:
913   case tgtok::XTail:
914   case tgtok::XSize:
915   case tgtok::XEmpty:
916   case tgtok::XCast:
917   case tgtok::XGetDagOp: { // Value ::= !unop '(' Value ')'
918     UnOpInit::UnaryOp Code;
919     RecTy *Type = nullptr;
920 
921     switch (Lex.getCode()) {
922     default: llvm_unreachable("Unhandled code!");
923     case tgtok::XCast:
924       Lex.Lex();  // eat the operation
925       Code = UnOpInit::CAST;
926 
927       Type = ParseOperatorType();
928 
929       if (!Type) {
930         TokError("did not get type for unary operator");
931         return nullptr;
932       }
933 
934       break;
935     case tgtok::XNOT:
936       Lex.Lex();  // eat the operation
937       Code = UnOpInit::NOT;
938       Type = IntRecTy::get();
939       break;
940     case tgtok::XHead:
941       Lex.Lex();  // eat the operation
942       Code = UnOpInit::HEAD;
943       break;
944     case tgtok::XTail:
945       Lex.Lex();  // eat the operation
946       Code = UnOpInit::TAIL;
947       break;
948     case tgtok::XSize:
949       Lex.Lex();
950       Code = UnOpInit::SIZE;
951       Type = IntRecTy::get();
952       break;
953     case tgtok::XEmpty:
954       Lex.Lex();  // eat the operation
955       Code = UnOpInit::EMPTY;
956       Type = IntRecTy::get();
957       break;
958     case tgtok::XGetDagOp:
959       Lex.Lex();  // eat the operation
960       if (Lex.getCode() == tgtok::less) {
961         // Parse an optional type suffix, so that you can say
962         // !getdagop<BaseClass>(someDag) as a shorthand for
963         // !cast<BaseClass>(!getdagop(someDag)).
964         Type = ParseOperatorType();
965 
966         if (!Type) {
967           TokError("did not get type for unary operator");
968           return nullptr;
969         }
970 
971         if (!isa<RecordRecTy>(Type)) {
972           TokError("type for !getdagop must be a record type");
973           // but keep parsing, to consume the operand
974         }
975       } else {
976         Type = RecordRecTy::get({});
977       }
978       Code = UnOpInit::GETDAGOP;
979       break;
980     }
981     if (!consume(tgtok::l_paren)) {
982       TokError("expected '(' after unary operator");
983       return nullptr;
984     }
985 
986     Init *LHS = ParseValue(CurRec);
987     if (!LHS) return nullptr;
988 
989     if (Code == UnOpInit::EMPTY || Code == UnOpInit::SIZE) {
990       ListInit *LHSl = dyn_cast<ListInit>(LHS);
991       StringInit *LHSs = dyn_cast<StringInit>(LHS);
992       DagInit *LHSd = dyn_cast<DagInit>(LHS);
993       TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
994       if (!LHSl && !LHSs && !LHSd && !LHSt) {
995         TokError("expected string, list, or dag type argument in unary operator");
996         return nullptr;
997       }
998       if (LHSt) {
999         ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1000         StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
1001         DagRecTy *DType = dyn_cast<DagRecTy>(LHSt->getType());
1002         if (!LType && !SType && !DType) {
1003           TokError("expected string, list, or dag type argument in unary operator");
1004           return nullptr;
1005         }
1006       }
1007     }
1008 
1009     if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
1010       ListInit *LHSl = dyn_cast<ListInit>(LHS);
1011       TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1012       if (!LHSl && !LHSt) {
1013         TokError("expected list type argument in unary operator");
1014         return nullptr;
1015       }
1016       if (LHSt) {
1017         ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1018         if (!LType) {
1019           TokError("expected list type argument in unary operator");
1020           return nullptr;
1021         }
1022       }
1023 
1024       if (LHSl && LHSl->empty()) {
1025         TokError("empty list argument in unary operator");
1026         return nullptr;
1027       }
1028       if (LHSl) {
1029         Init *Item = LHSl->getElement(0);
1030         TypedInit *Itemt = dyn_cast<TypedInit>(Item);
1031         if (!Itemt) {
1032           TokError("untyped list element in unary operator");
1033           return nullptr;
1034         }
1035         Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
1036                                         : ListRecTy::get(Itemt->getType());
1037       } else {
1038         assert(LHSt && "expected list type argument in unary operator");
1039         ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1040         Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
1041       }
1042     }
1043 
1044     if (!consume(tgtok::r_paren)) {
1045       TokError("expected ')' in unary operator");
1046       return nullptr;
1047     }
1048     return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec);
1049   }
1050 
1051   case tgtok::XIsA: {
1052     // Value ::= !isa '<' Type '>' '(' Value ')'
1053     Lex.Lex(); // eat the operation
1054 
1055     RecTy *Type = ParseOperatorType();
1056     if (!Type)
1057       return nullptr;
1058 
1059     if (!consume(tgtok::l_paren)) {
1060       TokError("expected '(' after type of !isa");
1061       return nullptr;
1062     }
1063 
1064     Init *LHS = ParseValue(CurRec);
1065     if (!LHS)
1066       return nullptr;
1067 
1068     if (!consume(tgtok::r_paren)) {
1069       TokError("expected ')' in !isa");
1070       return nullptr;
1071     }
1072 
1073     return (IsAOpInit::get(Type, LHS))->Fold();
1074   }
1075 
1076   case tgtok::XConcat:
1077   case tgtok::XADD:
1078   case tgtok::XSUB:
1079   case tgtok::XMUL:
1080   case tgtok::XAND:
1081   case tgtok::XOR:
1082   case tgtok::XXOR:
1083   case tgtok::XSRA:
1084   case tgtok::XSRL:
1085   case tgtok::XSHL:
1086   case tgtok::XEq:
1087   case tgtok::XNe:
1088   case tgtok::XLe:
1089   case tgtok::XLt:
1090   case tgtok::XGe:
1091   case tgtok::XGt:
1092   case tgtok::XListConcat:
1093   case tgtok::XListSplat:
1094   case tgtok::XStrConcat:
1095   case tgtok::XInterleave:
1096   case tgtok::XSetDagOp: { // Value ::= !binop '(' Value ',' Value ')'
1097     tgtok::TokKind OpTok = Lex.getCode();
1098     SMLoc OpLoc = Lex.getLoc();
1099     Lex.Lex();  // eat the operation
1100 
1101     BinOpInit::BinaryOp Code;
1102     switch (OpTok) {
1103     default: llvm_unreachable("Unhandled code!");
1104     case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
1105     case tgtok::XADD:    Code = BinOpInit::ADD; break;
1106     case tgtok::XSUB:    Code = BinOpInit::SUB; break;
1107     case tgtok::XMUL:    Code = BinOpInit::MUL; break;
1108     case tgtok::XAND:    Code = BinOpInit::AND; break;
1109     case tgtok::XOR:     Code = BinOpInit::OR; break;
1110     case tgtok::XXOR:    Code = BinOpInit::XOR; break;
1111     case tgtok::XSRA:    Code = BinOpInit::SRA; break;
1112     case tgtok::XSRL:    Code = BinOpInit::SRL; break;
1113     case tgtok::XSHL:    Code = BinOpInit::SHL; break;
1114     case tgtok::XEq:     Code = BinOpInit::EQ; break;
1115     case tgtok::XNe:     Code = BinOpInit::NE; break;
1116     case tgtok::XLe:     Code = BinOpInit::LE; break;
1117     case tgtok::XLt:     Code = BinOpInit::LT; break;
1118     case tgtok::XGe:     Code = BinOpInit::GE; break;
1119     case tgtok::XGt:     Code = BinOpInit::GT; break;
1120     case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break;
1121     case tgtok::XListSplat:  Code = BinOpInit::LISTSPLAT; break;
1122     case tgtok::XStrConcat:  Code = BinOpInit::STRCONCAT; break;
1123     case tgtok::XInterleave: Code = BinOpInit::INTERLEAVE; break;
1124     case tgtok::XSetDagOp:   Code = BinOpInit::SETDAGOP; break;
1125     }
1126 
1127     RecTy *Type = nullptr;
1128     RecTy *ArgType = nullptr;
1129     switch (OpTok) {
1130     default:
1131       llvm_unreachable("Unhandled code!");
1132     case tgtok::XConcat:
1133     case tgtok::XSetDagOp:
1134       Type = DagRecTy::get();
1135       ArgType = DagRecTy::get();
1136       break;
1137     case tgtok::XAND:
1138     case tgtok::XOR:
1139     case tgtok::XXOR:
1140     case tgtok::XSRA:
1141     case tgtok::XSRL:
1142     case tgtok::XSHL:
1143     case tgtok::XADD:
1144     case tgtok::XSUB:
1145     case tgtok::XMUL:
1146       Type = IntRecTy::get();
1147       ArgType = IntRecTy::get();
1148       break;
1149     case tgtok::XEq:
1150     case tgtok::XNe:
1151       Type = BitRecTy::get();
1152       // ArgType for Eq / Ne is not known at this point
1153       break;
1154     case tgtok::XLe:
1155     case tgtok::XLt:
1156     case tgtok::XGe:
1157     case tgtok::XGt:
1158       Type = BitRecTy::get();
1159       ArgType = IntRecTy::get();
1160       break;
1161     case tgtok::XListConcat:
1162       // We don't know the list type until we parse the first argument
1163       ArgType = ItemType;
1164       break;
1165     case tgtok::XListSplat:
1166       // Can't do any typechecking until we parse the first argument.
1167       break;
1168     case tgtok::XStrConcat:
1169       Type = StringRecTy::get();
1170       ArgType = StringRecTy::get();
1171       break;
1172     case tgtok::XInterleave:
1173       Type = StringRecTy::get();
1174       // The first argument type is not yet known.
1175     }
1176 
1177     if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1178       Error(OpLoc, Twine("expected value of type '") +
1179                    ItemType->getAsString() + "', got '" +
1180                    Type->getAsString() + "'");
1181       return nullptr;
1182     }
1183 
1184     if (!consume(tgtok::l_paren)) {
1185       TokError("expected '(' after binary operator");
1186       return nullptr;
1187     }
1188 
1189     SmallVector<Init*, 2> InitList;
1190 
1191     // Note that this loop consumes an arbitrary number of arguments.
1192     // The actual count is checked later.
1193     for (;;) {
1194       SMLoc InitLoc = Lex.getLoc();
1195       InitList.push_back(ParseValue(CurRec, ArgType));
1196       if (!InitList.back()) return nullptr;
1197 
1198       TypedInit *InitListBack = dyn_cast<TypedInit>(InitList.back());
1199       if (!InitListBack) {
1200         Error(OpLoc, Twine("expected value to be a typed value, got '" +
1201                            InitList.back()->getAsString() + "'"));
1202         return nullptr;
1203       }
1204       RecTy *ListType = InitListBack->getType();
1205 
1206       if (!ArgType) {
1207         // Argument type must be determined from the argument itself.
1208         ArgType = ListType;
1209 
1210         switch (Code) {
1211         case BinOpInit::LISTCONCAT:
1212           if (!isa<ListRecTy>(ArgType)) {
1213             Error(InitLoc, Twine("expected a list, got value of type '") +
1214                            ArgType->getAsString() + "'");
1215             return nullptr;
1216           }
1217           break;
1218         case BinOpInit::LISTSPLAT:
1219           if (ItemType && InitList.size() == 1) {
1220             if (!isa<ListRecTy>(ItemType)) {
1221               Error(OpLoc,
1222                     Twine("expected output type to be a list, got type '") +
1223                         ItemType->getAsString() + "'");
1224               return nullptr;
1225             }
1226             if (!ArgType->getListTy()->typeIsConvertibleTo(ItemType)) {
1227               Error(OpLoc, Twine("expected first arg type to be '") +
1228                                ArgType->getAsString() +
1229                                "', got value of type '" +
1230                                cast<ListRecTy>(ItemType)
1231                                    ->getElementType()
1232                                    ->getAsString() +
1233                                "'");
1234               return nullptr;
1235             }
1236           }
1237           if (InitList.size() == 2 && !isa<IntRecTy>(ArgType)) {
1238             Error(InitLoc, Twine("expected second parameter to be an int, got "
1239                                  "value of type '") +
1240                                ArgType->getAsString() + "'");
1241             return nullptr;
1242           }
1243           ArgType = nullptr; // Broken invariant: types not identical.
1244           break;
1245         case BinOpInit::EQ:
1246         case BinOpInit::NE:
1247           if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
1248               !ArgType->typeIsConvertibleTo(StringRecTy::get())) {
1249             Error(InitLoc, Twine("expected int, bits, or string; got value of "
1250                                  "type '") + ArgType->getAsString() + "'");
1251             return nullptr;
1252           }
1253           break;
1254         case BinOpInit::INTERLEAVE:
1255           switch (InitList.size()) {
1256           case 1: // First argument must be a list of strings or integers.
1257             if (ArgType != StringRecTy::get()->getListTy() &&
1258                 !ArgType->typeIsConvertibleTo(IntRecTy::get()->getListTy())) {
1259               Error(InitLoc, Twine("expected list of string, int, bits, or bit; "
1260                                    "got value of type '") +
1261                                    ArgType->getAsString() + "'");
1262               return nullptr;
1263             }
1264             break;
1265           case 2: // Second argument must be a string.
1266             if (!isa<StringRecTy>(ArgType)) {
1267               Error(InitLoc, Twine("expected second argument to be a string, "
1268                                    "got value of type '") +
1269                                  ArgType->getAsString() + "'");
1270               return nullptr;
1271             }
1272             break;
1273           default: ;
1274           }
1275           ArgType = nullptr; // Broken invariant: types not identical.
1276           break;
1277         default: llvm_unreachable("other ops have fixed argument types");
1278         }
1279 
1280       } else {
1281         // Desired argument type is a known and in ArgType.
1282         RecTy *Resolved = resolveTypes(ArgType, ListType);
1283         if (!Resolved) {
1284           Error(InitLoc, Twine("expected value of type '") +
1285                              ArgType->getAsString() + "', got '" +
1286                              ListType->getAsString() + "'");
1287           return nullptr;
1288         }
1289         if (Code != BinOpInit::ADD && Code != BinOpInit::SUB &&
1290             Code != BinOpInit::AND && Code != BinOpInit::OR &&
1291             Code != BinOpInit::XOR && Code != BinOpInit::SRA &&
1292             Code != BinOpInit::SRL && Code != BinOpInit::SHL &&
1293             Code != BinOpInit::MUL)
1294           ArgType = Resolved;
1295       }
1296 
1297       // Deal with BinOps whose arguments have different types, by
1298       // rewriting ArgType in between them.
1299       switch (Code) {
1300         case BinOpInit::SETDAGOP:
1301           // After parsing the first dag argument, switch to expecting
1302           // a record, with no restriction on its superclasses.
1303           ArgType = RecordRecTy::get({});
1304           break;
1305         default:
1306           break;
1307       }
1308 
1309       if (!consume(tgtok::comma))
1310         break;
1311     }
1312 
1313     if (!consume(tgtok::r_paren)) {
1314       TokError("expected ')' in operator");
1315       return nullptr;
1316     }
1317 
1318     // listconcat returns a list with type of the argument.
1319     if (Code == BinOpInit::LISTCONCAT)
1320       Type = ArgType;
1321     // listsplat returns a list of type of the *first* argument.
1322     if (Code == BinOpInit::LISTSPLAT)
1323       Type = cast<TypedInit>(InitList.front())->getType()->getListTy();
1324 
1325     // We allow multiple operands to associative operators like !strconcat as
1326     // shorthand for nesting them.
1327     if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT ||
1328         Code == BinOpInit::CONCAT || Code == BinOpInit::ADD ||
1329         Code == BinOpInit::AND || Code == BinOpInit::OR ||
1330         Code == BinOpInit::XOR || Code == BinOpInit::MUL) {
1331       while (InitList.size() > 2) {
1332         Init *RHS = InitList.pop_back_val();
1333         RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec);
1334         InitList.back() = RHS;
1335       }
1336     }
1337 
1338     if (InitList.size() == 2)
1339       return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
1340           ->Fold(CurRec);
1341 
1342     Error(OpLoc, "expected two operands to operator");
1343     return nullptr;
1344   }
1345 
1346   case tgtok::XForEach: {
1347     // Value ::= !foreach '(' Id ',' Value ',' Value ')'
1348     SMLoc OpLoc = Lex.getLoc();
1349     Lex.Lex(); // eat the operation
1350     if (Lex.getCode() != tgtok::l_paren) {
1351       TokError("expected '(' after !foreach");
1352       return nullptr;
1353     }
1354 
1355     if (Lex.Lex() != tgtok::Id) { // eat the '('
1356       TokError("first argument of !foreach must be an identifier");
1357       return nullptr;
1358     }
1359 
1360     Init *LHS = StringInit::get(Lex.getCurStrVal());
1361     Lex.Lex();
1362 
1363     if (CurRec && CurRec->getValue(LHS)) {
1364       TokError((Twine("iteration variable '") + LHS->getAsString() +
1365                 "' already defined")
1366                    .str());
1367       return nullptr;
1368     }
1369 
1370     if (!consume(tgtok::comma)) { // eat the id
1371       TokError("expected ',' in ternary operator");
1372       return nullptr;
1373     }
1374 
1375     Init *MHS = ParseValue(CurRec);
1376     if (!MHS)
1377       return nullptr;
1378 
1379     if (!consume(tgtok::comma)) {
1380       TokError("expected ',' in ternary operator");
1381       return nullptr;
1382     }
1383 
1384     TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1385     if (!MHSt) {
1386       TokError("could not get type of !foreach input");
1387       return nullptr;
1388     }
1389 
1390     RecTy *InEltType = nullptr;
1391     RecTy *OutEltType = nullptr;
1392     bool IsDAG = false;
1393 
1394     if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) {
1395       InEltType = InListTy->getElementType();
1396       if (ItemType) {
1397         if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) {
1398           OutEltType = OutListTy->getElementType();
1399         } else {
1400           Error(OpLoc,
1401                 "expected value of type '" + Twine(ItemType->getAsString()) +
1402                 "', but got !foreach of list type");
1403           return nullptr;
1404         }
1405       }
1406     } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) {
1407       InEltType = InDagTy;
1408       if (ItemType && !isa<DagRecTy>(ItemType)) {
1409         Error(OpLoc,
1410               "expected value of type '" + Twine(ItemType->getAsString()) +
1411               "', but got !foreach of dag type");
1412         return nullptr;
1413       }
1414       IsDAG = true;
1415     } else {
1416       TokError("!foreach must have list or dag input");
1417       return nullptr;
1418     }
1419 
1420     // We need to create a temporary record to provide a scope for the
1421     // iteration variable.
1422     std::unique_ptr<Record> ParseRecTmp;
1423     Record *ParseRec = CurRec;
1424     if (!ParseRec) {
1425       ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1426       ParseRec = ParseRecTmp.get();
1427     }
1428 
1429     ParseRec->addValue(RecordVal(LHS, InEltType, false));
1430     Init *RHS = ParseValue(ParseRec, OutEltType);
1431     ParseRec->removeValue(LHS);
1432     if (!RHS)
1433       return nullptr;
1434 
1435     if (!consume(tgtok::r_paren)) {
1436       TokError("expected ')' in binary operator");
1437       return nullptr;
1438     }
1439 
1440     RecTy *OutType;
1441     if (IsDAG) {
1442       OutType = InEltType;
1443     } else {
1444       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1445       if (!RHSt) {
1446         TokError("could not get type of !foreach result");
1447         return nullptr;
1448       }
1449       OutType = RHSt->getType()->getListTy();
1450     }
1451 
1452     return (TernOpInit::get(TernOpInit::FOREACH, LHS, MHS, RHS, OutType))
1453         ->Fold(CurRec);
1454   }
1455 
1456   case tgtok::XDag:
1457   case tgtok::XIf:
1458   case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1459     TernOpInit::TernaryOp Code;
1460     RecTy *Type = nullptr;
1461 
1462     tgtok::TokKind LexCode = Lex.getCode();
1463     Lex.Lex();  // eat the operation
1464     switch (LexCode) {
1465     default: llvm_unreachable("Unhandled code!");
1466     case tgtok::XDag:
1467       Code = TernOpInit::DAG;
1468       Type = DagRecTy::get();
1469       ItemType = nullptr;
1470       break;
1471     case tgtok::XIf:
1472       Code = TernOpInit::IF;
1473       break;
1474     case tgtok::XSubst:
1475       Code = TernOpInit::SUBST;
1476       break;
1477     }
1478     if (!consume(tgtok::l_paren)) {
1479       TokError("expected '(' after ternary operator");
1480       return nullptr;
1481     }
1482 
1483     Init *LHS = ParseValue(CurRec);
1484     if (!LHS) return nullptr;
1485 
1486     if (!consume(tgtok::comma)) {
1487       TokError("expected ',' in ternary operator");
1488       return nullptr;
1489     }
1490 
1491     SMLoc MHSLoc = Lex.getLoc();
1492     Init *MHS = ParseValue(CurRec, ItemType);
1493     if (!MHS)
1494       return nullptr;
1495 
1496     if (!consume(tgtok::comma)) {
1497       TokError("expected ',' in ternary operator");
1498       return nullptr;
1499     }
1500 
1501     SMLoc RHSLoc = Lex.getLoc();
1502     Init *RHS = ParseValue(CurRec, ItemType);
1503     if (!RHS)
1504       return nullptr;
1505 
1506     if (!consume(tgtok::r_paren)) {
1507       TokError("expected ')' in binary operator");
1508       return nullptr;
1509     }
1510 
1511     switch (LexCode) {
1512     default: llvm_unreachable("Unhandled code!");
1513     case tgtok::XDag: {
1514       TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1515       if (!MHSt && !isa<UnsetInit>(MHS)) {
1516         Error(MHSLoc, "could not determine type of the child list in !dag");
1517         return nullptr;
1518       }
1519       if (MHSt && !isa<ListRecTy>(MHSt->getType())) {
1520         Error(MHSLoc, Twine("expected list of children, got type '") +
1521                           MHSt->getType()->getAsString() + "'");
1522         return nullptr;
1523       }
1524 
1525       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1526       if (!RHSt && !isa<UnsetInit>(RHS)) {
1527         Error(RHSLoc, "could not determine type of the name list in !dag");
1528         return nullptr;
1529       }
1530       if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) {
1531         Error(RHSLoc, Twine("expected list<string>, got type '") +
1532                           RHSt->getType()->getAsString() + "'");
1533         return nullptr;
1534       }
1535 
1536       if (!MHSt && !RHSt) {
1537         Error(MHSLoc,
1538               "cannot have both unset children and unset names in !dag");
1539         return nullptr;
1540       }
1541       break;
1542     }
1543     case tgtok::XIf: {
1544       RecTy *MHSTy = nullptr;
1545       RecTy *RHSTy = nullptr;
1546 
1547       if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1548         MHSTy = MHSt->getType();
1549       if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1550         MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1551       if (isa<BitInit>(MHS))
1552         MHSTy = BitRecTy::get();
1553 
1554       if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1555         RHSTy = RHSt->getType();
1556       if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1557         RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1558       if (isa<BitInit>(RHS))
1559         RHSTy = BitRecTy::get();
1560 
1561       // For UnsetInit, it's typed from the other hand.
1562       if (isa<UnsetInit>(MHS))
1563         MHSTy = RHSTy;
1564       if (isa<UnsetInit>(RHS))
1565         RHSTy = MHSTy;
1566 
1567       if (!MHSTy || !RHSTy) {
1568         TokError("could not get type for !if");
1569         return nullptr;
1570       }
1571 
1572       Type = resolveTypes(MHSTy, RHSTy);
1573       if (!Type) {
1574         TokError(Twine("inconsistent types '") + MHSTy->getAsString() +
1575                  "' and '" + RHSTy->getAsString() + "' for !if");
1576         return nullptr;
1577       }
1578       break;
1579     }
1580     case tgtok::XSubst: {
1581       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1582       if (!RHSt) {
1583         TokError("could not get type for !subst");
1584         return nullptr;
1585       }
1586       Type = RHSt->getType();
1587       break;
1588     }
1589     }
1590     return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
1591   }
1592 
1593   case tgtok::XCond:
1594     return ParseOperationCond(CurRec, ItemType);
1595 
1596   case tgtok::XFoldl: {
1597     // Value ::= !foldl '(' Value ',' Value ',' Id ',' Id ',' Expr ')'
1598     Lex.Lex(); // eat the operation
1599     if (!consume(tgtok::l_paren)) {
1600       TokError("expected '(' after !foldl");
1601       return nullptr;
1602     }
1603 
1604     Init *StartUntyped = ParseValue(CurRec);
1605     if (!StartUntyped)
1606       return nullptr;
1607 
1608     TypedInit *Start = dyn_cast<TypedInit>(StartUntyped);
1609     if (!Start) {
1610       TokError(Twine("could not get type of !foldl start: '") +
1611                StartUntyped->getAsString() + "'");
1612       return nullptr;
1613     }
1614 
1615     if (!consume(tgtok::comma)) {
1616       TokError("expected ',' in !foldl");
1617       return nullptr;
1618     }
1619 
1620     Init *ListUntyped = ParseValue(CurRec);
1621     if (!ListUntyped)
1622       return nullptr;
1623 
1624     TypedInit *List = dyn_cast<TypedInit>(ListUntyped);
1625     if (!List) {
1626       TokError(Twine("could not get type of !foldl list: '") +
1627                ListUntyped->getAsString() + "'");
1628       return nullptr;
1629     }
1630 
1631     ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType());
1632     if (!ListType) {
1633       TokError(Twine("!foldl list must be a list, but is of type '") +
1634                List->getType()->getAsString());
1635       return nullptr;
1636     }
1637 
1638     if (Lex.getCode() != tgtok::comma) {
1639       TokError("expected ',' in !foldl");
1640       return nullptr;
1641     }
1642 
1643     if (Lex.Lex() != tgtok::Id) { // eat the ','
1644       TokError("third argument of !foldl must be an identifier");
1645       return nullptr;
1646     }
1647 
1648     Init *A = StringInit::get(Lex.getCurStrVal());
1649     if (CurRec && CurRec->getValue(A)) {
1650       TokError((Twine("left !foldl variable '") + A->getAsString() +
1651                 "' already defined")
1652                    .str());
1653       return nullptr;
1654     }
1655 
1656     if (Lex.Lex() != tgtok::comma) { // eat the id
1657       TokError("expected ',' in !foldl");
1658       return nullptr;
1659     }
1660 
1661     if (Lex.Lex() != tgtok::Id) { // eat the ','
1662       TokError("fourth argument of !foldl must be an identifier");
1663       return nullptr;
1664     }
1665 
1666     Init *B = StringInit::get(Lex.getCurStrVal());
1667     if (CurRec && CurRec->getValue(B)) {
1668       TokError((Twine("right !foldl variable '") + B->getAsString() +
1669                 "' already defined")
1670                    .str());
1671       return nullptr;
1672     }
1673 
1674     if (Lex.Lex() != tgtok::comma) { // eat the id
1675       TokError("expected ',' in !foldl");
1676       return nullptr;
1677     }
1678     Lex.Lex(); // eat the ','
1679 
1680     // We need to create a temporary record to provide a scope for the
1681     // two variables.
1682     std::unique_ptr<Record> ParseRecTmp;
1683     Record *ParseRec = CurRec;
1684     if (!ParseRec) {
1685       ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1686       ParseRec = ParseRecTmp.get();
1687     }
1688 
1689     ParseRec->addValue(RecordVal(A, Start->getType(), false));
1690     ParseRec->addValue(RecordVal(B, ListType->getElementType(), false));
1691     Init *ExprUntyped = ParseValue(ParseRec);
1692     ParseRec->removeValue(A);
1693     ParseRec->removeValue(B);
1694     if (!ExprUntyped)
1695       return nullptr;
1696 
1697     TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped);
1698     if (!Expr) {
1699       TokError("could not get type of !foldl expression");
1700       return nullptr;
1701     }
1702 
1703     if (Expr->getType() != Start->getType()) {
1704       TokError(Twine("!foldl expression must be of same type as start (") +
1705                Start->getType()->getAsString() + "), but is of type " +
1706                Expr->getType()->getAsString());
1707       return nullptr;
1708     }
1709 
1710     if (!consume(tgtok::r_paren)) {
1711       TokError("expected ')' in fold operator");
1712       return nullptr;
1713     }
1714 
1715     return FoldOpInit::get(Start, List, A, B, Expr, Start->getType())
1716         ->Fold(CurRec);
1717   }
1718   }
1719 }
1720 
1721 /// ParseOperatorType - Parse a type for an operator.  This returns
1722 /// null on error.
1723 ///
1724 /// OperatorType ::= '<' Type '>'
1725 ///
1726 RecTy *TGParser::ParseOperatorType() {
1727   RecTy *Type = nullptr;
1728 
1729   if (!consume(tgtok::less)) {
1730     TokError("expected type name for operator");
1731     return nullptr;
1732   }
1733 
1734   Type = ParseType();
1735 
1736   if (!Type) {
1737     TokError("expected type name for operator");
1738     return nullptr;
1739   }
1740 
1741   if (!consume(tgtok::greater)) {
1742     TokError("expected type name for operator");
1743     return nullptr;
1744   }
1745 
1746   return Type;
1747 }
1748 
1749 Init *TGParser::ParseOperationCond(Record *CurRec, RecTy *ItemType) {
1750   Lex.Lex();  // eat the operation 'cond'
1751 
1752   if (!consume(tgtok::l_paren)) {
1753     TokError("expected '(' after !cond operator");
1754     return nullptr;
1755   }
1756 
1757   // Parse through '[Case: Val,]+'
1758   SmallVector<Init *, 4> Case;
1759   SmallVector<Init *, 4> Val;
1760   while (true) {
1761     if (consume(tgtok::r_paren))
1762       break;
1763 
1764     Init *V = ParseValue(CurRec);
1765     if (!V)
1766       return nullptr;
1767     Case.push_back(V);
1768 
1769     if (!consume(tgtok::colon)) {
1770       TokError("expected ':'  following a condition in !cond operator");
1771       return nullptr;
1772     }
1773 
1774     V = ParseValue(CurRec, ItemType);
1775     if (!V)
1776       return nullptr;
1777     Val.push_back(V);
1778 
1779     if (consume(tgtok::r_paren))
1780       break;
1781 
1782     if (!consume(tgtok::comma)) {
1783       TokError("expected ',' or ')' following a value in !cond operator");
1784       return nullptr;
1785     }
1786   }
1787 
1788   if (Case.size() < 1) {
1789     TokError("there should be at least 1 'condition : value' in the !cond operator");
1790     return nullptr;
1791   }
1792 
1793   // resolve type
1794   RecTy *Type = nullptr;
1795   for (Init *V : Val) {
1796     RecTy *VTy = nullptr;
1797     if (TypedInit *Vt = dyn_cast<TypedInit>(V))
1798       VTy = Vt->getType();
1799     if (BitsInit *Vbits = dyn_cast<BitsInit>(V))
1800       VTy = BitsRecTy::get(Vbits->getNumBits());
1801     if (isa<BitInit>(V))
1802       VTy = BitRecTy::get();
1803 
1804     if (Type == nullptr) {
1805       if (!isa<UnsetInit>(V))
1806         Type = VTy;
1807     } else {
1808       if (!isa<UnsetInit>(V)) {
1809         RecTy *RType = resolveTypes(Type, VTy);
1810         if (!RType) {
1811           TokError(Twine("inconsistent types '") + Type->getAsString() +
1812                          "' and '" + VTy->getAsString() + "' for !cond");
1813           return nullptr;
1814         }
1815         Type = RType;
1816       }
1817     }
1818   }
1819 
1820   if (!Type) {
1821     TokError("could not determine type for !cond from its arguments");
1822     return nullptr;
1823   }
1824   return CondOpInit::get(Case, Val, Type)->Fold(CurRec);
1825 }
1826 
1827 /// ParseSimpleValue - Parse a tblgen value.  This returns null on error.
1828 ///
1829 ///   SimpleValue ::= IDValue
1830 ///   SimpleValue ::= INTVAL
1831 ///   SimpleValue ::= STRVAL+
1832 ///   SimpleValue ::= CODEFRAGMENT
1833 ///   SimpleValue ::= '?'
1834 ///   SimpleValue ::= '{' ValueList '}'
1835 ///   SimpleValue ::= ID '<' ValueListNE '>'
1836 ///   SimpleValue ::= '[' ValueList ']'
1837 ///   SimpleValue ::= '(' IDValue DagArgList ')'
1838 ///   SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1839 ///   SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1840 ///   SimpleValue ::= SUBTOK '(' Value ',' Value ')'
1841 ///   SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1842 ///   SimpleValue ::= SRATOK '(' Value ',' Value ')'
1843 ///   SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1844 ///   SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1845 ///   SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
1846 ///   SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1847 ///   SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
1848 ///
1849 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1850                                  IDParseMode Mode) {
1851   Init *R = nullptr;
1852   switch (Lex.getCode()) {
1853   default: TokError("Unknown or reserved token when parsing a value"); break;
1854 
1855   case tgtok::TrueVal:
1856     R = IntInit::get(1);
1857     Lex.Lex();
1858     break;
1859   case tgtok::FalseVal:
1860     R = IntInit::get(0);
1861     Lex.Lex();
1862     break;
1863   case tgtok::IntVal:
1864     R = IntInit::get(Lex.getCurIntVal());
1865     Lex.Lex();
1866     break;
1867   case tgtok::BinaryIntVal: {
1868     auto BinaryVal = Lex.getCurBinaryIntVal();
1869     SmallVector<Init*, 16> Bits(BinaryVal.second);
1870     for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1871       Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1872     R = BitsInit::get(Bits);
1873     Lex.Lex();
1874     break;
1875   }
1876   case tgtok::StrVal: {
1877     std::string Val = Lex.getCurStrVal();
1878     Lex.Lex();
1879 
1880     // Handle multiple consecutive concatenated strings.
1881     while (Lex.getCode() == tgtok::StrVal) {
1882       Val += Lex.getCurStrVal();
1883       Lex.Lex();
1884     }
1885 
1886     R = StringInit::get(Val);
1887     break;
1888   }
1889   case tgtok::CodeFragment:
1890     R = CodeInit::get(Lex.getCurStrVal(), Lex.getLoc());
1891     Lex.Lex();
1892     break;
1893   case tgtok::question:
1894     R = UnsetInit::get();
1895     Lex.Lex();
1896     break;
1897   case tgtok::Id: {
1898     SMLoc NameLoc = Lex.getLoc();
1899     StringInit *Name = StringInit::get(Lex.getCurStrVal());
1900     if (Lex.Lex() != tgtok::less)  // consume the Id.
1901       return ParseIDValue(CurRec, Name, NameLoc, Mode);    // Value ::= IDValue
1902 
1903     // Value ::= ID '<' ValueListNE '>'
1904     if (Lex.Lex() == tgtok::greater) {
1905       TokError("expected non-empty value list");
1906       return nullptr;
1907     }
1908 
1909     // This is a CLASS<initvalslist> expression.  This is supposed to synthesize
1910     // a new anonymous definition, deriving from CLASS<initvalslist> with no
1911     // body.
1912     Record *Class = Records.getClass(Name->getValue());
1913     if (!Class) {
1914       Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'");
1915       return nullptr;
1916     }
1917 
1918     SmallVector<Init *, 8> Args;
1919     ParseValueList(Args, CurRec, Class);
1920     if (Args.empty()) return nullptr;
1921 
1922     if (!consume(tgtok::greater)) {
1923       TokError("expected '>' at end of value list");
1924       return nullptr;
1925     }
1926 
1927     // Typecheck the template arguments list
1928     ArrayRef<Init *> ExpectedArgs = Class->getTemplateArgs();
1929     if (ExpectedArgs.size() < Args.size()) {
1930       Error(NameLoc,
1931             "More template args specified than expected");
1932       return nullptr;
1933     }
1934 
1935     for (unsigned i = 0, e = ExpectedArgs.size(); i != e; ++i) {
1936       RecordVal *ExpectedArg = Class->getValue(ExpectedArgs[i]);
1937       if (i < Args.size()) {
1938         if (TypedInit *TI = dyn_cast<TypedInit>(Args[i])) {
1939           RecTy *ExpectedType = ExpectedArg->getType();
1940           if (!TI->getType()->typeIsConvertibleTo(ExpectedType)) {
1941             Error(NameLoc,
1942                   "Value specified for template argument #" + Twine(i) + " (" +
1943                   ExpectedArg->getNameInitAsString() + ") is of type '" +
1944                   TI->getType()->getAsString() + "', expected '" +
1945                   ExpectedType->getAsString() + "': " + TI->getAsString());
1946             return nullptr;
1947           }
1948           continue;
1949         }
1950       } else if (ExpectedArg->getValue()->isComplete())
1951         continue;
1952 
1953       Error(NameLoc,
1954             "Value not specified for template argument #" + Twine(i) + " (" +
1955             ExpectedArgs[i]->getAsUnquotedString() + ")");
1956       return nullptr;
1957     }
1958 
1959     return VarDefInit::get(Class, Args)->Fold();
1960   }
1961   case tgtok::l_brace: {           // Value ::= '{' ValueList '}'
1962     SMLoc BraceLoc = Lex.getLoc();
1963     Lex.Lex(); // eat the '{'
1964     SmallVector<Init*, 16> Vals;
1965 
1966     if (Lex.getCode() != tgtok::r_brace) {
1967       ParseValueList(Vals, CurRec);
1968       if (Vals.empty()) return nullptr;
1969     }
1970     if (!consume(tgtok::r_brace)) {
1971       TokError("expected '}' at end of bit list value");
1972       return nullptr;
1973     }
1974 
1975     SmallVector<Init *, 16> NewBits;
1976 
1977     // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1978     // first.  We'll first read everything in to a vector, then we can reverse
1979     // it to get the bits in the correct order for the BitsInit value.
1980     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1981       // FIXME: The following two loops would not be duplicated
1982       //        if the API was a little more orthogonal.
1983 
1984       // bits<n> values are allowed to initialize n bits.
1985       if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1986         for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1987           NewBits.push_back(BI->getBit((e - i) - 1));
1988         continue;
1989       }
1990       // bits<n> can also come from variable initializers.
1991       if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
1992         if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
1993           for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
1994             NewBits.push_back(VI->getBit((e - i) - 1));
1995           continue;
1996         }
1997         // Fallthrough to try convert this to a bit.
1998       }
1999       // All other values must be convertible to just a single bit.
2000       Init *Bit = Vals[i]->getCastTo(BitRecTy::get());
2001       if (!Bit) {
2002         Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
2003               ") is not convertable to a bit");
2004         return nullptr;
2005       }
2006       NewBits.push_back(Bit);
2007     }
2008     std::reverse(NewBits.begin(), NewBits.end());
2009     return BitsInit::get(NewBits);
2010   }
2011   case tgtok::l_square: {          // Value ::= '[' ValueList ']'
2012     Lex.Lex(); // eat the '['
2013     SmallVector<Init*, 16> Vals;
2014 
2015     RecTy *DeducedEltTy = nullptr;
2016     ListRecTy *GivenListTy = nullptr;
2017 
2018     if (ItemType) {
2019       ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
2020       if (!ListType) {
2021         TokError(Twine("Encountered a list when expecting a ") +
2022                  ItemType->getAsString());
2023         return nullptr;
2024       }
2025       GivenListTy = ListType;
2026     }
2027 
2028     if (Lex.getCode() != tgtok::r_square) {
2029       ParseValueList(Vals, CurRec, nullptr,
2030                      GivenListTy ? GivenListTy->getElementType() : nullptr);
2031       if (Vals.empty()) return nullptr;
2032     }
2033     if (!consume(tgtok::r_square)) {
2034       TokError("expected ']' at end of list value");
2035       return nullptr;
2036     }
2037 
2038     RecTy *GivenEltTy = nullptr;
2039     if (consume(tgtok::less)) {
2040       // Optional list element type
2041       GivenEltTy = ParseType();
2042       if (!GivenEltTy) {
2043         // Couldn't parse element type
2044         return nullptr;
2045       }
2046 
2047       if (!consume(tgtok::greater)) {
2048         TokError("expected '>' at end of list element type");
2049         return nullptr;
2050       }
2051     }
2052 
2053     // Check elements
2054     RecTy *EltTy = nullptr;
2055     for (Init *V : Vals) {
2056       TypedInit *TArg = dyn_cast<TypedInit>(V);
2057       if (TArg) {
2058         if (EltTy) {
2059           EltTy = resolveTypes(EltTy, TArg->getType());
2060           if (!EltTy) {
2061             TokError("Incompatible types in list elements");
2062             return nullptr;
2063           }
2064         } else {
2065           EltTy = TArg->getType();
2066         }
2067       }
2068     }
2069 
2070     if (GivenEltTy) {
2071       if (EltTy) {
2072         // Verify consistency
2073         if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
2074           TokError("Incompatible types in list elements");
2075           return nullptr;
2076         }
2077       }
2078       EltTy = GivenEltTy;
2079     }
2080 
2081     if (!EltTy) {
2082       if (!ItemType) {
2083         TokError("No type for list");
2084         return nullptr;
2085       }
2086       DeducedEltTy = GivenListTy->getElementType();
2087     } else {
2088       // Make sure the deduced type is compatible with the given type
2089       if (GivenListTy) {
2090         if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
2091           TokError(Twine("Element type mismatch for list: element type '") +
2092                    EltTy->getAsString() + "' not convertible to '" +
2093                    GivenListTy->getElementType()->getAsString());
2094           return nullptr;
2095         }
2096       }
2097       DeducedEltTy = EltTy;
2098     }
2099 
2100     return ListInit::get(Vals, DeducedEltTy);
2101   }
2102   case tgtok::l_paren: {         // Value ::= '(' IDValue DagArgList ')'
2103     Lex.Lex();   // eat the '('
2104     if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast &&
2105         Lex.getCode() != tgtok::question && Lex.getCode() != tgtok::XGetDagOp) {
2106       TokError("expected identifier in dag init");
2107       return nullptr;
2108     }
2109 
2110     Init *Operator = ParseValue(CurRec);
2111     if (!Operator) return nullptr;
2112 
2113     // If the operator name is present, parse it.
2114     StringInit *OperatorName = nullptr;
2115     if (consume(tgtok::colon)) {
2116       if (Lex.getCode() != tgtok::VarName) { // eat the ':'
2117         TokError("expected variable name in dag operator");
2118         return nullptr;
2119       }
2120       OperatorName = StringInit::get(Lex.getCurStrVal());
2121       Lex.Lex();  // eat the VarName.
2122     }
2123 
2124     SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs;
2125     if (Lex.getCode() != tgtok::r_paren) {
2126       ParseDagArgList(DagArgs, CurRec);
2127       if (DagArgs.empty()) return nullptr;
2128     }
2129 
2130     if (!consume(tgtok::r_paren)) {
2131       TokError("expected ')' in dag init");
2132       return nullptr;
2133     }
2134 
2135     return DagInit::get(Operator, OperatorName, DagArgs);
2136   }
2137 
2138   case tgtok::XHead:
2139   case tgtok::XTail:
2140   case tgtok::XSize:
2141   case tgtok::XEmpty:
2142   case tgtok::XCast:
2143   case tgtok::XGetDagOp: // Value ::= !unop '(' Value ')'
2144   case tgtok::XIsA:
2145   case tgtok::XConcat:
2146   case tgtok::XDag:
2147   case tgtok::XADD:
2148   case tgtok::XSUB:
2149   case tgtok::XMUL:
2150   case tgtok::XNOT:
2151   case tgtok::XAND:
2152   case tgtok::XOR:
2153   case tgtok::XXOR:
2154   case tgtok::XSRA:
2155   case tgtok::XSRL:
2156   case tgtok::XSHL:
2157   case tgtok::XEq:
2158   case tgtok::XNe:
2159   case tgtok::XLe:
2160   case tgtok::XLt:
2161   case tgtok::XGe:
2162   case tgtok::XGt:
2163   case tgtok::XListConcat:
2164   case tgtok::XListSplat:
2165   case tgtok::XStrConcat:
2166   case tgtok::XInterleave:
2167   case tgtok::XSetDagOp: // Value ::= !binop '(' Value ',' Value ')'
2168   case tgtok::XIf:
2169   case tgtok::XCond:
2170   case tgtok::XFoldl:
2171   case tgtok::XForEach:
2172   case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
2173     return ParseOperation(CurRec, ItemType);
2174   }
2175   }
2176 
2177   return R;
2178 }
2179 
2180 /// ParseValue - Parse a tblgen value.  This returns null on error.
2181 ///
2182 ///   Value       ::= SimpleValue ValueSuffix*
2183 ///   ValueSuffix ::= '{' BitList '}'
2184 ///   ValueSuffix ::= '[' BitList ']'
2185 ///   ValueSuffix ::= '.' ID
2186 ///
2187 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
2188   Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
2189   if (!Result) return nullptr;
2190 
2191   // Parse the suffixes now if present.
2192   while (true) {
2193     switch (Lex.getCode()) {
2194     default: return Result;
2195     case tgtok::l_brace: {
2196       if (Mode == ParseNameMode)
2197         // This is the beginning of the object body.
2198         return Result;
2199 
2200       SMLoc CurlyLoc = Lex.getLoc();
2201       Lex.Lex(); // eat the '{'
2202       SmallVector<unsigned, 16> Ranges;
2203       ParseRangeList(Ranges);
2204       if (Ranges.empty()) return nullptr;
2205 
2206       // Reverse the bitlist.
2207       std::reverse(Ranges.begin(), Ranges.end());
2208       Result = Result->convertInitializerBitRange(Ranges);
2209       if (!Result) {
2210         Error(CurlyLoc, "Invalid bit range for value");
2211         return nullptr;
2212       }
2213 
2214       // Eat the '}'.
2215       if (!consume(tgtok::r_brace)) {
2216         TokError("expected '}' at end of bit range list");
2217         return nullptr;
2218       }
2219       break;
2220     }
2221     case tgtok::l_square: {
2222       SMLoc SquareLoc = Lex.getLoc();
2223       Lex.Lex(); // eat the '['
2224       SmallVector<unsigned, 16> Ranges;
2225       ParseRangeList(Ranges);
2226       if (Ranges.empty()) return nullptr;
2227 
2228       Result = Result->convertInitListSlice(Ranges);
2229       if (!Result) {
2230         Error(SquareLoc, "Invalid range for list slice");
2231         return nullptr;
2232       }
2233 
2234       // Eat the ']'.
2235       if (!consume(tgtok::r_square)) {
2236         TokError("expected ']' at end of list slice");
2237         return nullptr;
2238       }
2239       break;
2240     }
2241     case tgtok::dot: {
2242       if (Lex.Lex() != tgtok::Id) { // eat the .
2243         TokError("expected field identifier after '.'");
2244         return nullptr;
2245       }
2246       StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2247       if (!Result->getFieldType(FieldName)) {
2248         TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
2249                  Result->getAsString() + "'");
2250         return nullptr;
2251       }
2252       Result = FieldInit::get(Result, FieldName)->Fold(CurRec);
2253       Lex.Lex();  // eat field name
2254       break;
2255     }
2256 
2257     case tgtok::paste:
2258       SMLoc PasteLoc = Lex.getLoc();
2259       TypedInit *LHS = dyn_cast<TypedInit>(Result);
2260       if (!LHS) {
2261         Error(PasteLoc, "LHS of paste is not typed!");
2262         return nullptr;
2263       }
2264 
2265       // Check if it's a 'listA # listB'
2266       if (isa<ListRecTy>(LHS->getType())) {
2267         Lex.Lex();  // Eat the '#'.
2268 
2269         assert(Mode == ParseValueMode && "encountered paste of lists in name");
2270 
2271         switch (Lex.getCode()) {
2272         case tgtok::colon:
2273         case tgtok::semi:
2274         case tgtok::l_brace:
2275           Result = LHS; // trailing paste, ignore.
2276           break;
2277         default:
2278           Init *RHSResult = ParseValue(CurRec, ItemType, ParseValueMode);
2279           if (!RHSResult)
2280             return nullptr;
2281           Result = BinOpInit::getListConcat(LHS, RHSResult);
2282           break;
2283         }
2284         break;
2285       }
2286 
2287       // Create a !strconcat() operation, first casting each operand to
2288       // a string if necessary.
2289       if (LHS->getType() != StringRecTy::get()) {
2290         auto CastLHS = dyn_cast<TypedInit>(
2291             UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get())
2292                 ->Fold(CurRec));
2293         if (!CastLHS) {
2294           Error(PasteLoc,
2295                 Twine("can't cast '") + LHS->getAsString() + "' to string");
2296           return nullptr;
2297         }
2298         LHS = CastLHS;
2299       }
2300 
2301       TypedInit *RHS = nullptr;
2302 
2303       Lex.Lex();  // Eat the '#'.
2304       switch (Lex.getCode()) {
2305       case tgtok::colon:
2306       case tgtok::semi:
2307       case tgtok::l_brace:
2308         // These are all of the tokens that can begin an object body.
2309         // Some of these can also begin values but we disallow those cases
2310         // because they are unlikely to be useful.
2311 
2312         // Trailing paste, concat with an empty string.
2313         RHS = StringInit::get("");
2314         break;
2315 
2316       default:
2317         Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode);
2318         if (!RHSResult)
2319           return nullptr;
2320         RHS = dyn_cast<TypedInit>(RHSResult);
2321         if (!RHS) {
2322           Error(PasteLoc, "RHS of paste is not typed!");
2323           return nullptr;
2324         }
2325 
2326         if (RHS->getType() != StringRecTy::get()) {
2327           auto CastRHS = dyn_cast<TypedInit>(
2328               UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get())
2329                   ->Fold(CurRec));
2330           if (!CastRHS) {
2331             Error(PasteLoc,
2332                   Twine("can't cast '") + RHS->getAsString() + "' to string");
2333             return nullptr;
2334           }
2335           RHS = CastRHS;
2336         }
2337 
2338         break;
2339       }
2340 
2341       Result = BinOpInit::getStrConcat(LHS, RHS);
2342       break;
2343     }
2344   }
2345 }
2346 
2347 /// ParseDagArgList - Parse the argument list for a dag literal expression.
2348 ///
2349 ///    DagArg     ::= Value (':' VARNAME)?
2350 ///    DagArg     ::= VARNAME
2351 ///    DagArgList ::= DagArg
2352 ///    DagArgList ::= DagArgList ',' DagArg
2353 void TGParser::ParseDagArgList(
2354     SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result,
2355     Record *CurRec) {
2356 
2357   while (true) {
2358     // DagArg ::= VARNAME
2359     if (Lex.getCode() == tgtok::VarName) {
2360       // A missing value is treated like '?'.
2361       StringInit *VarName = StringInit::get(Lex.getCurStrVal());
2362       Result.emplace_back(UnsetInit::get(), VarName);
2363       Lex.Lex();
2364     } else {
2365       // DagArg ::= Value (':' VARNAME)?
2366       Init *Val = ParseValue(CurRec);
2367       if (!Val) {
2368         Result.clear();
2369         return;
2370       }
2371 
2372       // If the variable name is present, add it.
2373       StringInit *VarName = nullptr;
2374       if (Lex.getCode() == tgtok::colon) {
2375         if (Lex.Lex() != tgtok::VarName) { // eat the ':'
2376           TokError("expected variable name in dag literal");
2377           Result.clear();
2378           return;
2379         }
2380         VarName = StringInit::get(Lex.getCurStrVal());
2381         Lex.Lex();  // eat the VarName.
2382       }
2383 
2384       Result.push_back(std::make_pair(Val, VarName));
2385     }
2386     if (!consume(tgtok::comma))
2387       break;
2388   }
2389 }
2390 
2391 /// ParseValueList - Parse a comma separated list of values, returning them as a
2392 /// vector.  Note that this always expects to be able to parse at least one
2393 /// value.  It returns an empty list if this is not possible.
2394 ///
2395 ///   ValueList ::= Value (',' Value)
2396 ///
2397 void TGParser::ParseValueList(SmallVectorImpl<Init*> &Result, Record *CurRec,
2398                               Record *ArgsRec, RecTy *EltTy) {
2399   RecTy *ItemType = EltTy;
2400   unsigned int ArgN = 0;
2401   if (ArgsRec && !EltTy) {
2402     ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2403     if (TArgs.empty()) {
2404       TokError("template argument provided to non-template class");
2405       Result.clear();
2406       return;
2407     }
2408     const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2409     if (!RV) {
2410       errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
2411         << ")\n";
2412     }
2413     assert(RV && "Template argument record not found??");
2414     ItemType = RV->getType();
2415     ++ArgN;
2416   }
2417   Result.push_back(ParseValue(CurRec, ItemType));
2418   if (!Result.back()) {
2419     Result.clear();
2420     return;
2421   }
2422 
2423   while (consume(tgtok::comma)) {
2424     // ignore trailing comma for lists
2425     if (Lex.getCode() == tgtok::r_square)
2426       return;
2427 
2428     if (ArgsRec && !EltTy) {
2429       ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2430       if (ArgN >= TArgs.size()) {
2431         TokError("too many template arguments");
2432         Result.clear();
2433         return;
2434       }
2435       const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2436       assert(RV && "Template argument record not found??");
2437       ItemType = RV->getType();
2438       ++ArgN;
2439     }
2440     Result.push_back(ParseValue(CurRec, ItemType));
2441     if (!Result.back()) {
2442       Result.clear();
2443       return;
2444     }
2445   }
2446 }
2447 
2448 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
2449 /// empty string on error.  This can happen in a number of different context's,
2450 /// including within a def or in the template args for a def (which which case
2451 /// CurRec will be non-null) and within the template args for a multiclass (in
2452 /// which case CurRec will be null, but CurMultiClass will be set).  This can
2453 /// also happen within a def that is within a multiclass, which will set both
2454 /// CurRec and CurMultiClass.
2455 ///
2456 ///  Declaration ::= FIELD? Type ID ('=' Value)?
2457 ///
2458 Init *TGParser::ParseDeclaration(Record *CurRec,
2459                                        bool ParsingTemplateArgs) {
2460   // Read the field prefix if present.
2461   bool HasField = consume(tgtok::Field);
2462 
2463   RecTy *Type = ParseType();
2464   if (!Type) return nullptr;
2465 
2466   if (Lex.getCode() != tgtok::Id) {
2467     TokError("Expected identifier in declaration");
2468     return nullptr;
2469   }
2470 
2471   std::string Str = Lex.getCurStrVal();
2472   if (Str == "NAME") {
2473     TokError("'" + Str + "' is a reserved variable name");
2474     return nullptr;
2475   }
2476 
2477   SMLoc IdLoc = Lex.getLoc();
2478   Init *DeclName = StringInit::get(Str);
2479   Lex.Lex();
2480 
2481   if (ParsingTemplateArgs) {
2482     if (CurRec)
2483       DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
2484     else
2485       assert(CurMultiClass);
2486     if (CurMultiClass)
2487       DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
2488                              "::");
2489   }
2490 
2491   // Add the value.
2492   if (AddValue(CurRec, IdLoc, RecordVal(DeclName, IdLoc, Type, HasField)))
2493     return nullptr;
2494 
2495   // If a value is present, parse it.
2496   if (consume(tgtok::equal)) {
2497     SMLoc ValLoc = Lex.getLoc();
2498     Init *Val = ParseValue(CurRec, Type);
2499     if (!Val ||
2500         SetValue(CurRec, ValLoc, DeclName, None, Val))
2501       // Return the name, even if an error is thrown.  This is so that we can
2502       // continue to make some progress, even without the value having been
2503       // initialized.
2504       return DeclName;
2505   }
2506 
2507   return DeclName;
2508 }
2509 
2510 /// ParseForeachDeclaration - Read a foreach declaration, returning
2511 /// the name of the declared object or a NULL Init on error.  Return
2512 /// the name of the parsed initializer list through ForeachListName.
2513 ///
2514 ///  ForeachDeclaration ::= ID '=' '{' RangeList '}'
2515 ///  ForeachDeclaration ::= ID '=' RangePiece
2516 ///  ForeachDeclaration ::= ID '=' Value
2517 ///
2518 VarInit *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) {
2519   if (Lex.getCode() != tgtok::Id) {
2520     TokError("Expected identifier in foreach declaration");
2521     return nullptr;
2522   }
2523 
2524   Init *DeclName = StringInit::get(Lex.getCurStrVal());
2525   Lex.Lex();
2526 
2527   // If a value is present, parse it.
2528   if (!consume(tgtok::equal)) {
2529     TokError("Expected '=' in foreach declaration");
2530     return nullptr;
2531   }
2532 
2533   RecTy *IterType = nullptr;
2534   SmallVector<unsigned, 16> Ranges;
2535 
2536   switch (Lex.getCode()) {
2537   case tgtok::l_brace: { // '{' RangeList '}'
2538     Lex.Lex(); // eat the '{'
2539     ParseRangeList(Ranges);
2540     if (!consume(tgtok::r_brace)) {
2541       TokError("expected '}' at end of bit range list");
2542       return nullptr;
2543     }
2544     break;
2545   }
2546 
2547   default: {
2548     SMLoc ValueLoc = Lex.getLoc();
2549     Init *I = ParseValue(nullptr);
2550     if (!I)
2551       return nullptr;
2552 
2553     TypedInit *TI = dyn_cast<TypedInit>(I);
2554     if (TI && isa<ListRecTy>(TI->getType())) {
2555       ForeachListValue = I;
2556       IterType = cast<ListRecTy>(TI->getType())->getElementType();
2557       break;
2558     }
2559 
2560     if (TI) {
2561       if (ParseRangePiece(Ranges, TI))
2562         return nullptr;
2563       break;
2564     }
2565 
2566     std::string Type;
2567     if (TI)
2568       Type = (Twine("' of type '") + TI->getType()->getAsString()).str();
2569     Error(ValueLoc, "expected a list, got '" + I->getAsString() + Type + "'");
2570     if (CurMultiClass) {
2571       PrintNote({}, "references to multiclass template arguments cannot be "
2572                 "resolved at this time");
2573     }
2574     return nullptr;
2575   }
2576   }
2577 
2578 
2579   if (!Ranges.empty()) {
2580     assert(!IterType && "Type already initialized?");
2581     IterType = IntRecTy::get();
2582     std::vector<Init*> Values;
2583     for (unsigned R : Ranges)
2584       Values.push_back(IntInit::get(R));
2585     ForeachListValue = ListInit::get(Values, IterType);
2586   }
2587 
2588   if (!IterType)
2589     return nullptr;
2590 
2591   return VarInit::get(DeclName, IterType);
2592 }
2593 
2594 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
2595 /// sequence of template-declarations in <>'s.  If CurRec is non-null, these are
2596 /// template args for a def, which may or may not be in a multiclass.  If null,
2597 /// these are the template args for a multiclass.
2598 ///
2599 ///    TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
2600 ///
2601 bool TGParser::ParseTemplateArgList(Record *CurRec) {
2602   assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
2603   Lex.Lex(); // eat the '<'
2604 
2605   Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
2606 
2607   // Read the first declaration.
2608   Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2609   if (!TemplArg)
2610     return true;
2611 
2612   TheRecToAddTo->addTemplateArg(TemplArg);
2613 
2614   while (consume(tgtok::comma)) {
2615     // Read the following declarations.
2616     SMLoc Loc = Lex.getLoc();
2617     TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2618     if (!TemplArg)
2619       return true;
2620 
2621     if (TheRecToAddTo->isTemplateArg(TemplArg))
2622       return Error(Loc, "template argument with the same name has already been "
2623                         "defined");
2624 
2625     TheRecToAddTo->addTemplateArg(TemplArg);
2626   }
2627 
2628   if (!consume(tgtok::greater))
2629     return TokError("expected '>' at end of template argument list");
2630   return false;
2631 }
2632 
2633 /// ParseBodyItem - Parse a single item at within the body of a def or class.
2634 ///
2635 ///   BodyItem ::= Declaration ';'
2636 ///   BodyItem ::= LET ID OptionalBitList '=' Value ';'
2637 ///   BodyItem ::= Defvar
2638 bool TGParser::ParseBodyItem(Record *CurRec) {
2639   if (Lex.getCode() == tgtok::Defvar)
2640     return ParseDefvar();
2641 
2642   if (Lex.getCode() != tgtok::Let) {
2643     if (!ParseDeclaration(CurRec, false))
2644       return true;
2645 
2646     if (!consume(tgtok::semi))
2647       return TokError("expected ';' after declaration");
2648     return false;
2649   }
2650 
2651   // LET ID OptionalRangeList '=' Value ';'
2652   if (Lex.Lex() != tgtok::Id)
2653     return TokError("expected field identifier after let");
2654 
2655   SMLoc IdLoc = Lex.getLoc();
2656   StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2657   Lex.Lex();  // eat the field name.
2658 
2659   SmallVector<unsigned, 16> BitList;
2660   if (ParseOptionalBitList(BitList))
2661     return true;
2662   std::reverse(BitList.begin(), BitList.end());
2663 
2664   if (!consume(tgtok::equal))
2665     return TokError("expected '=' in let expression");
2666 
2667   RecordVal *Field = CurRec->getValue(FieldName);
2668   if (!Field)
2669     return TokError("Value '" + FieldName->getValue() + "' unknown!");
2670 
2671   RecTy *Type = Field->getType();
2672   if (!BitList.empty() && isa<BitsRecTy>(Type)) {
2673     // When assigning to a subset of a 'bits' object, expect the RHS to have
2674     // the type of that subset instead of the type of the whole object.
2675     Type = BitsRecTy::get(BitList.size());
2676   }
2677 
2678   Init *Val = ParseValue(CurRec, Type);
2679   if (!Val) return true;
2680 
2681   if (!consume(tgtok::semi))
2682     return TokError("expected ';' after let expression");
2683 
2684   return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
2685 }
2686 
2687 /// ParseBody - Read the body of a class or def.  Return true on error, false on
2688 /// success.
2689 ///
2690 ///   Body     ::= ';'
2691 ///   Body     ::= '{' BodyList '}'
2692 ///   BodyList BodyItem*
2693 ///
2694 bool TGParser::ParseBody(Record *CurRec) {
2695   // If this is a null definition, just eat the semi and return.
2696   if (consume(tgtok::semi))
2697     return false;
2698 
2699   if (!consume(tgtok::l_brace))
2700     return TokError("Expected ';' or '{' to start body");
2701 
2702   // An object body introduces a new scope for local variables.
2703   TGLocalVarScope *BodyScope = PushLocalScope();
2704 
2705   while (Lex.getCode() != tgtok::r_brace)
2706     if (ParseBodyItem(CurRec))
2707       return true;
2708 
2709   PopLocalScope(BodyScope);
2710 
2711   // Eat the '}'.
2712   Lex.Lex();
2713   return false;
2714 }
2715 
2716 /// Apply the current let bindings to \a CurRec.
2717 /// \returns true on error, false otherwise.
2718 bool TGParser::ApplyLetStack(Record *CurRec) {
2719   for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
2720     for (LetRecord &LR : LetInfo)
2721       if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
2722         return true;
2723   return false;
2724 }
2725 
2726 bool TGParser::ApplyLetStack(RecordsEntry &Entry) {
2727   if (Entry.Rec)
2728     return ApplyLetStack(Entry.Rec.get());
2729 
2730   for (auto &E : Entry.Loop->Entries) {
2731     if (ApplyLetStack(E))
2732       return true;
2733   }
2734 
2735   return false;
2736 }
2737 
2738 /// ParseObjectBody - Parse the body of a def or class.  This consists of an
2739 /// optional ClassList followed by a Body.  CurRec is the current def or class
2740 /// that is being parsed.
2741 ///
2742 ///   ObjectBody      ::= BaseClassList Body
2743 ///   BaseClassList   ::= /*empty*/
2744 ///   BaseClassList   ::= ':' BaseClassListNE
2745 ///   BaseClassListNE ::= SubClassRef (',' SubClassRef)*
2746 ///
2747 bool TGParser::ParseObjectBody(Record *CurRec) {
2748   // If there is a baseclass list, read it.
2749   if (consume(tgtok::colon)) {
2750 
2751     // Read all of the subclasses.
2752     SubClassReference SubClass = ParseSubClassReference(CurRec, false);
2753     while (true) {
2754       // Check for error.
2755       if (!SubClass.Rec) return true;
2756 
2757       // Add it.
2758       if (AddSubClass(CurRec, SubClass))
2759         return true;
2760 
2761       if (!consume(tgtok::comma))
2762         break;
2763       SubClass = ParseSubClassReference(CurRec, false);
2764     }
2765   }
2766 
2767   if (ApplyLetStack(CurRec))
2768     return true;
2769 
2770   return ParseBody(CurRec);
2771 }
2772 
2773 /// ParseDef - Parse and return a top level or multiclass def, return the record
2774 /// corresponding to it.  This returns null on error.
2775 ///
2776 ///   DefInst ::= DEF ObjectName ObjectBody
2777 ///
2778 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2779   SMLoc DefLoc = Lex.getLoc();
2780   assert(Lex.getCode() == tgtok::Def && "Unknown tok");
2781   Lex.Lex();  // Eat the 'def' token.
2782 
2783   // Parse ObjectName and make a record for it.
2784   std::unique_ptr<Record> CurRec;
2785   Init *Name = ParseObjectName(CurMultiClass);
2786   if (!Name)
2787     return true;
2788 
2789   if (isa<UnsetInit>(Name))
2790     CurRec = std::make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records,
2791                                  /*Anonymous=*/true);
2792   else
2793     CurRec = std::make_unique<Record>(Name, DefLoc, Records);
2794 
2795   if (ParseObjectBody(CurRec.get()))
2796     return true;
2797 
2798   return addEntry(std::move(CurRec));
2799 }
2800 
2801 /// ParseDefset - Parse a defset statement.
2802 ///
2803 ///   Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
2804 ///
2805 bool TGParser::ParseDefset() {
2806   assert(Lex.getCode() == tgtok::Defset);
2807   Lex.Lex(); // Eat the 'defset' token
2808 
2809   DefsetRecord Defset;
2810   Defset.Loc = Lex.getLoc();
2811   RecTy *Type = ParseType();
2812   if (!Type)
2813     return true;
2814   if (!isa<ListRecTy>(Type))
2815     return Error(Defset.Loc, "expected list type");
2816   Defset.EltTy = cast<ListRecTy>(Type)->getElementType();
2817 
2818   if (Lex.getCode() != tgtok::Id)
2819     return TokError("expected identifier");
2820   StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
2821   if (Records.getGlobal(DeclName->getValue()))
2822     return TokError("def or global variable of this name already exists");
2823 
2824   if (Lex.Lex() != tgtok::equal) // Eat the identifier
2825     return TokError("expected '='");
2826   if (Lex.Lex() != tgtok::l_brace) // Eat the '='
2827     return TokError("expected '{'");
2828   SMLoc BraceLoc = Lex.getLoc();
2829   Lex.Lex(); // Eat the '{'
2830 
2831   Defsets.push_back(&Defset);
2832   bool Err = ParseObjectList(nullptr);
2833   Defsets.pop_back();
2834   if (Err)
2835     return true;
2836 
2837   if (!consume(tgtok::r_brace)) {
2838     TokError("expected '}' at end of defset");
2839     return Error(BraceLoc, "to match this '{'");
2840   }
2841 
2842   Records.addExtraGlobal(DeclName->getValue(),
2843                          ListInit::get(Defset.Elements, Defset.EltTy));
2844   return false;
2845 }
2846 
2847 /// ParseDefvar - Parse a defvar statement.
2848 ///
2849 ///   Defvar ::= DEFVAR Id '=' Value ';'
2850 ///
2851 bool TGParser::ParseDefvar() {
2852   assert(Lex.getCode() == tgtok::Defvar);
2853   Lex.Lex(); // Eat the 'defvar' token
2854 
2855   if (Lex.getCode() != tgtok::Id)
2856     return TokError("expected identifier");
2857   StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
2858   if (CurLocalScope) {
2859     if (CurLocalScope->varAlreadyDefined(DeclName->getValue()))
2860       return TokError("local variable of this name already exists");
2861   } else {
2862     if (Records.getGlobal(DeclName->getValue()))
2863       return TokError("def or global variable of this name already exists");
2864   }
2865 
2866   Lex.Lex();
2867   if (!consume(tgtok::equal))
2868     return TokError("expected '='");
2869 
2870   Init *Value = ParseValue(nullptr);
2871   if (!Value)
2872     return true;
2873 
2874   if (!consume(tgtok::semi))
2875     return TokError("expected ';'");
2876 
2877   if (CurLocalScope)
2878     CurLocalScope->addVar(DeclName->getValue(), Value);
2879   else
2880     Records.addExtraGlobal(DeclName->getValue(), Value);
2881 
2882   return false;
2883 }
2884 
2885 /// ParseForeach - Parse a for statement.  Return the record corresponding
2886 /// to it.  This returns true on error.
2887 ///
2888 ///   Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2889 ///   Foreach ::= FOREACH Declaration IN Object
2890 ///
2891 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2892   SMLoc Loc = Lex.getLoc();
2893   assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2894   Lex.Lex();  // Eat the 'for' token.
2895 
2896   // Make a temporary object to record items associated with the for
2897   // loop.
2898   Init *ListValue = nullptr;
2899   VarInit *IterName = ParseForeachDeclaration(ListValue);
2900   if (!IterName)
2901     return TokError("expected declaration in for");
2902 
2903   if (!consume(tgtok::In))
2904     return TokError("Unknown tok");
2905 
2906   // Create a loop object and remember it.
2907   Loops.push_back(std::make_unique<ForeachLoop>(Loc, IterName, ListValue));
2908 
2909   // A foreach loop introduces a new scope for local variables.
2910   TGLocalVarScope *ForeachScope = PushLocalScope();
2911 
2912   if (Lex.getCode() != tgtok::l_brace) {
2913     // FOREACH Declaration IN Object
2914     if (ParseObject(CurMultiClass))
2915       return true;
2916   } else {
2917     SMLoc BraceLoc = Lex.getLoc();
2918     // Otherwise, this is a group foreach.
2919     Lex.Lex();  // eat the '{'.
2920 
2921     // Parse the object list.
2922     if (ParseObjectList(CurMultiClass))
2923       return true;
2924 
2925     if (!consume(tgtok::r_brace)) {
2926       TokError("expected '}' at end of foreach command");
2927       return Error(BraceLoc, "to match this '{'");
2928     }
2929   }
2930 
2931   PopLocalScope(ForeachScope);
2932 
2933   // Resolve the loop or store it for later resolution.
2934   std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
2935   Loops.pop_back();
2936 
2937   return addEntry(std::move(Loop));
2938 }
2939 
2940 /// ParseIf - Parse an if statement.
2941 ///
2942 ///   If ::= IF Value THEN IfBody
2943 ///   If ::= IF Value THEN IfBody ELSE IfBody
2944 ///
2945 bool TGParser::ParseIf(MultiClass *CurMultiClass) {
2946   SMLoc Loc = Lex.getLoc();
2947   assert(Lex.getCode() == tgtok::If && "Unknown tok");
2948   Lex.Lex(); // Eat the 'if' token.
2949 
2950   // Make a temporary object to record items associated with the for
2951   // loop.
2952   Init *Condition = ParseValue(nullptr);
2953   if (!Condition)
2954     return true;
2955 
2956   if (!consume(tgtok::Then))
2957     return TokError("Unknown tok");
2958 
2959   // We have to be able to save if statements to execute later, and they have
2960   // to live on the same stack as foreach loops. The simplest implementation
2961   // technique is to convert each 'then' or 'else' clause *into* a foreach
2962   // loop, over a list of length 0 or 1 depending on the condition, and with no
2963   // iteration variable being assigned.
2964 
2965   ListInit *EmptyList = ListInit::get({}, BitRecTy::get());
2966   ListInit *SingletonList = ListInit::get({BitInit::get(1)}, BitRecTy::get());
2967   RecTy *BitListTy = ListRecTy::get(BitRecTy::get());
2968 
2969   // The foreach containing the then-clause selects SingletonList if
2970   // the condition is true.
2971   Init *ThenClauseList =
2972       TernOpInit::get(TernOpInit::IF, Condition, SingletonList, EmptyList,
2973                       BitListTy)
2974           ->Fold(nullptr);
2975   Loops.push_back(std::make_unique<ForeachLoop>(Loc, nullptr, ThenClauseList));
2976 
2977   if (ParseIfBody(CurMultiClass, "then"))
2978     return true;
2979 
2980   std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
2981   Loops.pop_back();
2982 
2983   if (addEntry(std::move(Loop)))
2984     return true;
2985 
2986   // Now look for an optional else clause. The if-else syntax has the usual
2987   // dangling-else ambiguity, and by greedily matching an else here if we can,
2988   // we implement the usual resolution of pairing with the innermost unmatched
2989   // if.
2990   if (consume(tgtok::ElseKW)) {
2991     // The foreach containing the else-clause uses the same pair of lists as
2992     // above, but this time, selects SingletonList if the condition is *false*.
2993     Init *ElseClauseList =
2994         TernOpInit::get(TernOpInit::IF, Condition, EmptyList, SingletonList,
2995                         BitListTy)
2996             ->Fold(nullptr);
2997     Loops.push_back(
2998         std::make_unique<ForeachLoop>(Loc, nullptr, ElseClauseList));
2999 
3000     if (ParseIfBody(CurMultiClass, "else"))
3001       return true;
3002 
3003     Loop = std::move(Loops.back());
3004     Loops.pop_back();
3005 
3006     if (addEntry(std::move(Loop)))
3007       return true;
3008   }
3009 
3010   return false;
3011 }
3012 
3013 /// ParseIfBody - Parse the then-clause or else-clause of an if statement.
3014 ///
3015 ///   IfBody ::= Object
3016 ///   IfBody ::= '{' ObjectList '}'
3017 ///
3018 bool TGParser::ParseIfBody(MultiClass *CurMultiClass, StringRef Kind) {
3019   TGLocalVarScope *BodyScope = PushLocalScope();
3020 
3021   if (Lex.getCode() != tgtok::l_brace) {
3022     // A single object.
3023     if (ParseObject(CurMultiClass))
3024       return true;
3025   } else {
3026     SMLoc BraceLoc = Lex.getLoc();
3027     // A braced block.
3028     Lex.Lex(); // eat the '{'.
3029 
3030     // Parse the object list.
3031     if (ParseObjectList(CurMultiClass))
3032       return true;
3033 
3034     if (!consume(tgtok::r_brace)) {
3035       TokError("expected '}' at end of '" + Kind + "' clause");
3036       return Error(BraceLoc, "to match this '{'");
3037     }
3038   }
3039 
3040   PopLocalScope(BodyScope);
3041   return false;
3042 }
3043 
3044 /// ParseClass - Parse a tblgen class definition.
3045 ///
3046 ///   ClassInst ::= CLASS ID TemplateArgList? ObjectBody
3047 ///
3048 bool TGParser::ParseClass() {
3049   assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
3050   Lex.Lex();
3051 
3052   if (Lex.getCode() != tgtok::Id)
3053     return TokError("expected class name after 'class' keyword");
3054 
3055   Record *CurRec = Records.getClass(Lex.getCurStrVal());
3056   if (CurRec) {
3057     // If the body was previously defined, this is an error.
3058     if (!CurRec->getValues().empty() ||
3059         !CurRec->getSuperClasses().empty() ||
3060         !CurRec->getTemplateArgs().empty())
3061       return TokError("Class '" + CurRec->getNameInitAsString() +
3062                       "' already defined");
3063   } else {
3064     // If this is the first reference to this class, create and add it.
3065     auto NewRec =
3066         std::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records,
3067                                   /*Class=*/true);
3068     CurRec = NewRec.get();
3069     Records.addClass(std::move(NewRec));
3070   }
3071   Lex.Lex(); // eat the name.
3072 
3073   // If there are template args, parse them.
3074   if (Lex.getCode() == tgtok::less)
3075     if (ParseTemplateArgList(CurRec))
3076       return true;
3077 
3078   return ParseObjectBody(CurRec);
3079 }
3080 
3081 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
3082 /// of LetRecords.
3083 ///
3084 ///   LetList ::= LetItem (',' LetItem)*
3085 ///   LetItem ::= ID OptionalRangeList '=' Value
3086 ///
3087 void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) {
3088   do {
3089     if (Lex.getCode() != tgtok::Id) {
3090       TokError("expected identifier in let definition");
3091       Result.clear();
3092       return;
3093     }
3094 
3095     StringInit *Name = StringInit::get(Lex.getCurStrVal());
3096     SMLoc NameLoc = Lex.getLoc();
3097     Lex.Lex();  // Eat the identifier.
3098 
3099     // Check for an optional RangeList.
3100     SmallVector<unsigned, 16> Bits;
3101     if (ParseOptionalRangeList(Bits)) {
3102       Result.clear();
3103       return;
3104     }
3105     std::reverse(Bits.begin(), Bits.end());
3106 
3107     if (!consume(tgtok::equal)) {
3108       TokError("expected '=' in let expression");
3109       Result.clear();
3110       return;
3111     }
3112 
3113     Init *Val = ParseValue(nullptr);
3114     if (!Val) {
3115       Result.clear();
3116       return;
3117     }
3118 
3119     // Now that we have everything, add the record.
3120     Result.emplace_back(Name, Bits, Val, NameLoc);
3121   } while (consume(tgtok::comma));
3122 }
3123 
3124 /// ParseTopLevelLet - Parse a 'let' at top level.  This can be a couple of
3125 /// different related productions. This works inside multiclasses too.
3126 ///
3127 ///   Object ::= LET LetList IN '{' ObjectList '}'
3128 ///   Object ::= LET LetList IN Object
3129 ///
3130 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
3131   assert(Lex.getCode() == tgtok::Let && "Unexpected token");
3132   Lex.Lex();
3133 
3134   // Add this entry to the let stack.
3135   SmallVector<LetRecord, 8> LetInfo;
3136   ParseLetList(LetInfo);
3137   if (LetInfo.empty()) return true;
3138   LetStack.push_back(std::move(LetInfo));
3139 
3140   if (!consume(tgtok::In))
3141     return TokError("expected 'in' at end of top-level 'let'");
3142 
3143   TGLocalVarScope *LetScope = PushLocalScope();
3144 
3145   // If this is a scalar let, just handle it now
3146   if (Lex.getCode() != tgtok::l_brace) {
3147     // LET LetList IN Object
3148     if (ParseObject(CurMultiClass))
3149       return true;
3150   } else {   // Object ::= LETCommand '{' ObjectList '}'
3151     SMLoc BraceLoc = Lex.getLoc();
3152     // Otherwise, this is a group let.
3153     Lex.Lex();  // eat the '{'.
3154 
3155     // Parse the object list.
3156     if (ParseObjectList(CurMultiClass))
3157       return true;
3158 
3159     if (!consume(tgtok::r_brace)) {
3160       TokError("expected '}' at end of top level let command");
3161       return Error(BraceLoc, "to match this '{'");
3162     }
3163   }
3164 
3165   PopLocalScope(LetScope);
3166 
3167   // Outside this let scope, this let block is not active.
3168   LetStack.pop_back();
3169   return false;
3170 }
3171 
3172 /// ParseMultiClass - Parse a multiclass definition.
3173 ///
3174 ///  MultiClassInst ::= MULTICLASS ID TemplateArgList?
3175 ///                     ':' BaseMultiClassList '{' MultiClassObject+ '}'
3176 ///  MultiClassObject ::= DefInst
3177 ///  MultiClassObject ::= MultiClassInst
3178 ///  MultiClassObject ::= DefMInst
3179 ///  MultiClassObject ::= LETCommand '{' ObjectList '}'
3180 ///  MultiClassObject ::= LETCommand Object
3181 ///
3182 bool TGParser::ParseMultiClass() {
3183   assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
3184   Lex.Lex();  // Eat the multiclass token.
3185 
3186   if (Lex.getCode() != tgtok::Id)
3187     return TokError("expected identifier after multiclass for name");
3188   std::string Name = Lex.getCurStrVal();
3189 
3190   auto Result =
3191     MultiClasses.insert(std::make_pair(Name,
3192                     std::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
3193 
3194   if (!Result.second)
3195     return TokError("multiclass '" + Name + "' already defined");
3196 
3197   CurMultiClass = Result.first->second.get();
3198   Lex.Lex();  // Eat the identifier.
3199 
3200   // If there are template args, parse them.
3201   if (Lex.getCode() == tgtok::less)
3202     if (ParseTemplateArgList(nullptr))
3203       return true;
3204 
3205   bool inherits = false;
3206 
3207   // If there are submulticlasses, parse them.
3208   if (consume(tgtok::colon)) {
3209     inherits = true;
3210 
3211     // Read all of the submulticlasses.
3212     SubMultiClassReference SubMultiClass =
3213       ParseSubMultiClassReference(CurMultiClass);
3214     while (true) {
3215       // Check for error.
3216       if (!SubMultiClass.MC) return true;
3217 
3218       // Add it.
3219       if (AddSubMultiClass(CurMultiClass, SubMultiClass))
3220         return true;
3221 
3222       if (!consume(tgtok::comma))
3223         break;
3224       SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
3225     }
3226   }
3227 
3228   if (Lex.getCode() != tgtok::l_brace) {
3229     if (!inherits)
3230       return TokError("expected '{' in multiclass definition");
3231     if (!consume(tgtok::semi))
3232       return TokError("expected ';' in multiclass definition");
3233   } else {
3234     if (Lex.Lex() == tgtok::r_brace)  // eat the '{'.
3235       return TokError("multiclass must contain at least one def");
3236 
3237     // A multiclass body introduces a new scope for local variables.
3238     TGLocalVarScope *MulticlassScope = PushLocalScope();
3239 
3240     while (Lex.getCode() != tgtok::r_brace) {
3241       switch (Lex.getCode()) {
3242       default:
3243         return TokError("expected 'let', 'def', 'defm', 'defvar', 'foreach' "
3244                         "or 'if' in multiclass body");
3245       case tgtok::Let:
3246       case tgtok::Def:
3247       case tgtok::Defm:
3248       case tgtok::Defvar:
3249       case tgtok::Foreach:
3250       case tgtok::If:
3251         if (ParseObject(CurMultiClass))
3252           return true;
3253         break;
3254       }
3255     }
3256     Lex.Lex();  // eat the '}'.
3257 
3258     PopLocalScope(MulticlassScope);
3259   }
3260 
3261   CurMultiClass = nullptr;
3262   return false;
3263 }
3264 
3265 /// ParseDefm - Parse the instantiation of a multiclass.
3266 ///
3267 ///   DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
3268 ///
3269 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
3270   assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
3271   Lex.Lex(); // eat the defm
3272 
3273   Init *DefmName = ParseObjectName(CurMultiClass);
3274   if (!DefmName)
3275     return true;
3276   if (isa<UnsetInit>(DefmName)) {
3277     DefmName = Records.getNewAnonymousName();
3278     if (CurMultiClass)
3279       DefmName = BinOpInit::getStrConcat(
3280           VarInit::get(QualifiedNameOfImplicitName(CurMultiClass),
3281                        StringRecTy::get()),
3282           DefmName);
3283   }
3284 
3285   if (Lex.getCode() != tgtok::colon)
3286     return TokError("expected ':' after defm identifier");
3287 
3288   // Keep track of the new generated record definitions.
3289   std::vector<RecordsEntry> NewEntries;
3290 
3291   // This record also inherits from a regular class (non-multiclass)?
3292   bool InheritFromClass = false;
3293 
3294   // eat the colon.
3295   Lex.Lex();
3296 
3297   SMLoc SubClassLoc = Lex.getLoc();
3298   SubClassReference Ref = ParseSubClassReference(nullptr, true);
3299 
3300   while (true) {
3301     if (!Ref.Rec) return true;
3302 
3303     // To instantiate a multiclass, we need to first get the multiclass, then
3304     // instantiate each def contained in the multiclass with the SubClassRef
3305     // template parameters.
3306     MultiClass *MC = MultiClasses[std::string(Ref.Rec->getName())].get();
3307     assert(MC && "Didn't lookup multiclass correctly?");
3308     ArrayRef<Init*> TemplateVals = Ref.TemplateArgs;
3309 
3310     // Verify that the correct number of template arguments were specified.
3311     ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs();
3312     if (TArgs.size() < TemplateVals.size())
3313       return Error(SubClassLoc,
3314                    "more template args specified than multiclass expects");
3315 
3316     SubstStack Substs;
3317     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
3318       if (i < TemplateVals.size()) {
3319         Substs.emplace_back(TArgs[i], TemplateVals[i]);
3320       } else {
3321         Init *Default = MC->Rec.getValue(TArgs[i])->getValue();
3322         if (!Default->isComplete()) {
3323           return Error(SubClassLoc,
3324                        "value not specified for template argument #" +
3325                            Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
3326                            ") of multiclass '" + MC->Rec.getNameInitAsString() +
3327                            "'");
3328         }
3329         Substs.emplace_back(TArgs[i], Default);
3330       }
3331     }
3332 
3333     Substs.emplace_back(QualifiedNameOfImplicitName(MC), DefmName);
3334 
3335     if (resolve(MC->Entries, Substs, CurMultiClass == nullptr, &NewEntries,
3336                 &SubClassLoc))
3337       return true;
3338 
3339     if (!consume(tgtok::comma))
3340       break;
3341 
3342     if (Lex.getCode() != tgtok::Id)
3343       return TokError("expected identifier");
3344 
3345     SubClassLoc = Lex.getLoc();
3346 
3347     // A defm can inherit from regular classes (non-multiclass) as
3348     // long as they come in the end of the inheritance list.
3349     InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
3350 
3351     if (InheritFromClass)
3352       break;
3353 
3354     Ref = ParseSubClassReference(nullptr, true);
3355   }
3356 
3357   if (InheritFromClass) {
3358     // Process all the classes to inherit as if they were part of a
3359     // regular 'def' and inherit all record values.
3360     SubClassReference SubClass = ParseSubClassReference(nullptr, false);
3361     while (true) {
3362       // Check for error.
3363       if (!SubClass.Rec) return true;
3364 
3365       // Get the expanded definition prototypes and teach them about
3366       // the record values the current class to inherit has
3367       for (auto &E : NewEntries) {
3368         // Add it.
3369         if (AddSubClass(E, SubClass))
3370           return true;
3371       }
3372 
3373       if (!consume(tgtok::comma))
3374         break;
3375       SubClass = ParseSubClassReference(nullptr, false);
3376     }
3377   }
3378 
3379   for (auto &E : NewEntries) {
3380     if (ApplyLetStack(E))
3381       return true;
3382 
3383     addEntry(std::move(E));
3384   }
3385 
3386   if (!consume(tgtok::semi))
3387     return TokError("expected ';' at end of defm");
3388 
3389   return false;
3390 }
3391 
3392 /// ParseObject
3393 ///   Object ::= ClassInst
3394 ///   Object ::= DefInst
3395 ///   Object ::= MultiClassInst
3396 ///   Object ::= DefMInst
3397 ///   Object ::= LETCommand '{' ObjectList '}'
3398 ///   Object ::= LETCommand Object
3399 ///   Object ::= Defset
3400 ///   Object ::= Defvar
3401 bool TGParser::ParseObject(MultiClass *MC) {
3402   switch (Lex.getCode()) {
3403   default:
3404     return TokError("Expected class, def, defm, defset, multiclass, let, "
3405                     "foreach or if");
3406   case tgtok::Let:   return ParseTopLevelLet(MC);
3407   case tgtok::Def:   return ParseDef(MC);
3408   case tgtok::Foreach:   return ParseForeach(MC);
3409   case tgtok::If:    return ParseIf(MC);
3410   case tgtok::Defm:  return ParseDefm(MC);
3411   case tgtok::Defset:
3412     if (MC)
3413       return TokError("defset is not allowed inside multiclass");
3414     return ParseDefset();
3415   case tgtok::Defvar:
3416     return ParseDefvar();
3417   case tgtok::Class:
3418     if (MC)
3419       return TokError("class is not allowed inside multiclass");
3420     if (!Loops.empty())
3421       return TokError("class is not allowed inside foreach loop");
3422     return ParseClass();
3423   case tgtok::MultiClass:
3424     if (!Loops.empty())
3425       return TokError("multiclass is not allowed inside foreach loop");
3426     return ParseMultiClass();
3427   }
3428 }
3429 
3430 /// ParseObjectList
3431 ///   ObjectList :== Object*
3432 bool TGParser::ParseObjectList(MultiClass *MC) {
3433   while (isObjectStart(Lex.getCode())) {
3434     if (ParseObject(MC))
3435       return true;
3436   }
3437   return false;
3438 }
3439 
3440 bool TGParser::ParseFile() {
3441   Lex.Lex(); // Prime the lexer.
3442   if (ParseObjectList()) return true;
3443 
3444   // If we have unread input at the end of the file, report it.
3445   if (Lex.getCode() == tgtok::Eof)
3446     return false;
3447 
3448   return TokError("Unexpected input at top level");
3449 }
3450 
3451 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3452 LLVM_DUMP_METHOD void RecordsEntry::dump() const {
3453   if (Loop)
3454     Loop->dump();
3455   if (Rec)
3456     Rec->dump();
3457 }
3458 
3459 LLVM_DUMP_METHOD void ForeachLoop::dump() const {
3460   errs() << "foreach " << IterVar->getAsString() << " = "
3461          << ListValue->getAsString() << " in {\n";
3462 
3463   for (const auto &E : Entries)
3464     E.dump();
3465 
3466   errs() << "}\n";
3467 }
3468 
3469 LLVM_DUMP_METHOD void MultiClass::dump() const {
3470   errs() << "Record:\n";
3471   Rec.dump();
3472 
3473   errs() << "Defs:\n";
3474   for (const auto &E : Entries)
3475     E.dump();
3476 }
3477 #endif
3478