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