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