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