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