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